Home > front end >  Merge Json arrays using Jolt transform in NIFI
Merge Json arrays using Jolt transform in NIFI

Time:09-26

The Jolt transform should modify the input as shown, I need to push the data aggregated like that in to the DB based on the Key value as identifier. Input Json :

[
  {
    "Key": "991641500~2167767723",
    "itemNm": "2067875000"
  },
  {
    "Key": "991641500~2167767724",
    "itemNm": "2067875085"
  },
  {
    "Key": "991641500~2167767723",
    "itemNm": "2067875063"
  },
  {
    "Key": "991641500~2167767724",
    "itemNm": "2067875004"
  }
]

Output JSON:

The output JSON should be merged as follows, I need to have the key and the contents of those as elements of a JSon Array.

[
  {
    "Key": "991641500~2167767723",
    "Items": [
      {
        "itemNm": "2067875004"
      },
      {
        "itemNm": "2067875085"
      }
    ]
  },
  {
    "Key": "991641500~2167767724",
    "Items": [
      {
        "itemNm": "2067875000"
      },
      {
        "itemNm": "2067875063"
      }
    ]
  }
]

CodePudding user response:

You can use the following transformation spec :

[
  {
   // group attributes under common objects by their Key(@(1,Key))
    "operation": "shift",
    "spec": {
      "*": {
        "Key": "@(1,Key).&",
        "itemNm": "@(1,Key).items[&1].&"
      }
    }
  },
  {
   // get rid of object labels
    "operation": "shift",
    "spec": {
      "*": ""
    }
  },
  {
    // get rid of redundant null components of the arrays
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": "=recursivelySquashNulls"
    }
  },
  {
   // pick only single one from identical components of each "Key" array 
    "operation": "cardinality",
    "spec": {
      "*": {
        "Key": "ONE"
      }
    }
  }
]

the demo on the site enter image description here

  • Related