Search code examples
jsonjolt

JOLT : check if JSON contains special char , seperate json


I would like to ckeck if a JSON value contains special characters (in this case a pipe):

[
  {
    "item_original_no": "item1",
    "attribute": "PACKAGING_MATERIAL_1",
    "value": "PET"
  },
  {
    "item_original_no": "item2",
    "attribute": "colour",
    "value": "red|white|blue"
  }
]

if this is the case I would like to seperate the values. They should appear in different objects like in this target JSON

[
  {
    "item_original_no": "item1",
    "attribute": "PACKAGING_MATERIAL_1",
    "value": "PET"
  },
  {
    "item_original_no": "item2",
    "attribute": "colour",
    "value": "red"
  },
  {
    "item_original_no": "item2",
    "attribute": "colour",
    "value": "white"
  },
  {
    "item_original_no": "item2",
    "attribute": "colour",
    "value": "blue"
  }
]

I really do not know, if this is feasable with JOLT.

Thanks in adavance for your help and hint.


Solution

  • I don't know about the methods other than Jolt but it has a function called split, implementing it along with some upcoming shift transformations will handle what you need in this case such as

    [
      {
        "operation": "modify-overwrite-beta",
        "spec": {
          "*": {
            "value": "=split('\\|',@(1,&))" //splits the string by pipe chars if there exists any of them 
                                            //should be escaped by double pipes as a special character
          }
        }
      },
      {//the previous split function produces an array, namely "value"
        "operation": "shift",
        "spec": {
          "*": {
            "value": {//loop under the "value" array
              "*": {
                "@2": "@3,item_original_no.&1.Others",
                "@2,&1[&]": "@3,item_original_no.&1.&2"//partition by item_original_no along with indexes of the "value" array
              }
            }
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*": {
              "Others": {
                "*": "&3_&2.&",
                "value": { "": "" } //removes original "value" 
              },
              "*": "&2_&1.&"
            }
          }
        }
      },
      {//get rid of the object keys
        "operation": "shift",
        "spec": {
          "*": "[]"
        }
      }
    ]
    

    the demo on the site Jolt Transform Demo Using v0.1.1 is :

    enter image description here