Mohammadreza Khedri
Mohammadreza Khedri

Reputation: 2691

Jolt add key value to children

I am using NiFi Jolt Processor to transform some JSON data.

I need to create array of objects. I can get all objects from assets, but I want to add each date in parent to my object.

I have the following input JSON:

[
  {
    "date": "2022/01/09",
    "assets": [
      {
        "value": 1,
        "percentage": 0.1
      },
      {
        "value": 2,
        "percentage": 0.2
      }
    ],
    "liablities": []
  },
  {
    "date": "2022/01/08",
    "assets": [
      {
        "value": 3,
        "percentage": 0.3
      },
      {
        "value": 4,
        "percentage": 0.4
      }
    ],
    "liablities": []
  }
]

And this my expected output:

[
  {
    "value" : 1,
    "percentage" : 0.1,
    "date" : "2022/01/09"
  },
  {
    "value" : 2,
    "percentage" : 0.2,
    "date" : "2022/01/09"
  },
  {
    "value" : 3,
    "percentage" : 0.3,
    "date" : "2022/01/08"
 },
 {
   "value" : 4,
   "percentage" : 0.4,
   "date" : "2022/01/08"
  }
]

Upvotes: 1

Views: 860

Answers (2)

Sajad Hamreh
Sajad Hamreh

Reputation: 108

You Can use this Spec:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "assets": {
          "*": "[].@(2,date)"
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "@": "[&2]",
          "$": "[&2].date"
        }
      }
    }
  }
]

Upvotes: 1

Barbaros Özhan
Barbaros Özhan

Reputation: 65228

One alternative approach as applying two successive shift transformations in order to walk through the indexes of assets arrays, and pruning the generated keys 0,1 within the second step such as

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "assets": {
          "*": {
            "*": "&3[&1].&",
            "@(2,date)": "&3[&1].date"
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": ""
      }
    }
  }
]

The Demo has been prepared on https://jolt-demo.appspot.com/ :

enter image description here

Upvotes: 1

Related Questions