Search code examples
jsonapache-nifijolt

Jolt converts list of Objects to Arrays


Iam new to jolt. The transformation Iam trying to achieve is really simple.I have a json as shown below

{
  "Object": [
    {
      "date": "01-01-2021",
      "Sold": {
        "ItemType": "New",
        "ItemID": 1,
        "Description": "desc 1"
      }
    },
    {
      "date": "01-01-2021",
      "Sold": {
        "ItemType": "New 2",
        "ItemID": 2,
        "Description": "desc 2"
      }
    }
  ]
}

My expected output is


[{
        "ItemType": "New",
        "ItemID": 1,
}
,{

        "ItemType": "New 2",
        "ItemID": 2,

}]

But when I use this transform

[

  {
    "operation": "shift",
    "spec": {
      "Object": {
        "*": {
          "Sold": {
            "ItemType": "ItemType"
          }
        }
      }
    }
  }
]

The output I obtain is

{
  "ItemType" : [ "New", "New 2" ]
}

What is the mistake Iam making?


Solution

  • You should read about applying JOLT on JSON arrays, here for example. You need to reference the index array using [&2], which means look up the tree three levels: zero (Object), then one (Sold), then two (ItemType/ItemID) and use that as an index array in the output.

    [
      {
        "operation": "shift",
        "spec": {
          "Object": {
            "*": {
              "Sold": {
                "ItemType": "[&2].ItemType",
                "ItemID": "[&2].ItemID"
              }
            }
          }
        }
      }
    ]
    

    Output:

    [ {
      "ItemType" : "New",
      "ItemID" : 1
    }, {
      "ItemType" : "New 2",
      "ItemID" : 2
    } ]