Home > Software engineering >  JOLT transform an array of objects with nested array of objects
JOLT transform an array of objects with nested array of objects

Time:09-09

I am trying to create a JOLT transformation for the below input:

[
  {
    "attributes": [
      {
        "key": "A",
        "val": "10"
      },
      {
        "key": "B",
        "val": "20"
      }
    ]
  },
  {
    "attributes": [
      {
        "key": "A",
        "val": "30"
      },
      {
        "key": "B",
        "val": "40"
      }
    ]
  }
]

With the desired output of:

[
  {
    "NEW_A_KEY": "10",
    "NEW_B_KEY": "20"
  },
  {
    "NEW_A_KEY": "30",
    "NEW_B_KEY": "40"
  }
]

So far I was only able to build a specification for the case where the input JSON outter brackets are removed. Here it goes: input:

{
  "attributes": [
    {
      "key": "A",
      "val": "10"
    },
    {
      "key": "B",
      "val": "20"
    }
  ]
}

output:

{
  "NEW_A_KEY" : "10",
  "NEW_B_KEY" : "20"
}

specification:

[
  {
    "operation": "shift",
    "spec": {
      "attributes": {
        "*": {
          "key": {
            "A": {
              "#NEW_A_KEY": "[&3].key",
              "@(2,val)": "[&3].val"
            },
            "B": {
              "#NEW_B_KEY": "[&3].key",
              "@(2,val)": "[&3].val"
            }
          }
        }
      }
    }
  }, {
    "operation": "shift",
    "spec": {
      "*": {
        "@(0,val)": "@(1,key)"
      }
    }
  }
]

Putting the outter brackets on the input, which is the JSON I need to handle, I know that I need to add the extra naviation layer ("*"), however I'm not able to transform the input in the desired output. Any help would be much appreciated! Thanks!

CodePudding user response:

This spec will resolve your issue : I've used an if-else condition to check value is A or B and populated it accordingly -->

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": {
          "*": {
            "key": {
              "*": {
                "@(2,val)": "[&5].NEW_&_KEY"
              }
            }
          }
        }
      }
    }
  }
]
  • Related