Home > database >  Create array of simpler JSON objects from a nested JSON using jolt
Create array of simpler JSON objects from a nested JSON using jolt

Time:04-07

My input JSON is like

{
  "common": {
    "name": "abc"
  },
  "details": {
    "id": 4,
    "node": [
      {
        "name": "node1",
        "array2": []
      },
      {
        "name": "node2",
        "array2": [
          {
            "name": "node2_a2_1"
          }
        ]
      },
      {
        "name": "node3",
        "array2": [
          {
            "name": "node3_a2_1"
          },
          {
            "name": "node3_a2_2"
          },
          {
            "name": "node3_a2_3"
          }
        ]
      }
    ]
  }
}

What I want is for each leaf node in array2 (e.g. {"name": "node3_a2_1"}) I will traverse towards the root and add all common items and create an array of JSON objects without any nested object. So, the output I want is like

[
  {
    "common_name": "abc",
    "id": 4,
    "node_name": "node2",
    "name": "node2_a2_1"
  },
  {
    "common_name": "abc",
    "id": 4,
    "node_name": "node3",
    "name": "node3_a2_1"
  },
  {
    "common_name": "abc",
    "id": 4,
    "node_name": "node3",
    "name": "node3_a2_2"
  },
  {
    "common_name": "abc",
    "id": 4,
    "node_name": "node3",
    "name": "node3_a2_3"
  }
]

Could you please suggest how can I do that?

CodePudding user response:

You can walk through the array2 while picking values of each element from their original location in the JSON value.

For example; traverse } four times to grab the value of id by using @(4,id), and use @(3,name)[&1] as the common distinguishing identifier for each attribute such as

[
  {
    "operation": "shift",
    "spec": {
      "details": {
        "node": {
          "*": {
            "array2": {
              "*": {
                "@(5,common.name)": "@(3,name)[&1].common_name",
                "@(4,id)": "@(3,name)[&1].id",
                "@(2,name)": "@(3,name)[&1].node_name",
                "name": "@(3,name)[&1].&"
              }
            }
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": ""
      }
    }
  }
]

enter image description here

  • Related