Search code examples
jsonapache-nifijolt

Jolt - Transform from same key that can have string or an object value


I am trying to transform an input data where the same key-value could be string or object. But not able to figure out the correct transformation. Could someone please help. Thanks!

Input

[
  {
    "id": "id1",
    "location": {
      "value": "loc-123"
    }
  },
  {
    "id": "id2",
    "location": {
      "value": "loc-789"
    }
  },
  {
    "id": "id3",
    "location": "loc-666"
  }
]

Desired output:

[
  {
    "id": "id1",
    "loc": "loc-123"
  },
  {
    "id": "id2",
    "loc": "loc-789"
  },
  {
    "id": "id3",
    "loc": "loc-666"
  }
]

Solution

  • You can use the following transformation

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*": "[&1].&", // generates array-wise([ ]) results after going one (&1) level up 
                           // the tree to reach the level of indexes within the array
            "*ation": {
              "value": "[&2].&(1,1)",// increments +1 more level compared to the upper one
              "*": { // else case
                "@1": "[&3].&(2,1)"  // [&3]:increments +1 more level compared to the upper one
                                     // &(2,1):replicates the 1st piece represented 
                                     // by asterisk in "*ation" after going 2 levels up
              }
            }
          }
        }
      }
    ]
    

    the demo on the site http://jolt-demo.appspot.com/ is :

    enter image description here