Home > front end >  jolt transform json nested array into array of jsons
jolt transform json nested array into array of jsons

Time:07-22

I want to transform my json into another json with jolt. I have the following JSON :

{
  "centre": [
    {
      "name": "A",
      "accesses": [
        {
          "name": "a",
          "totalInputs": 140,
          "totalOutputs": 77
        },
        {
          "name": "b",
          "totalInputs": 1374,
          "totalOutputs": 1068
        }
      ]
    },
    {
      "name": "B",
      "accesses": [
        {
          "name": "c",
          "totalInputs": 610,
          "totalOutputs": 511
        }
      ]
    }
  ]
}

and I want to extract information from diferent levels of the tree and form a list of jsons. This is my expected output:

[
  {
    "center": "A",
    "accesses": "a",
    "totalInputs": 140,
    "totalOutputs": 77
  },
  {
    "center": "A",
    "accesses": "b",
    "totalInputs": 1374,
    "totalOutputs": 1068
  },
  {
    "center": "B",
    "accesses": "c",
    "totalInputs": 610,
    "totalOutputs": 511
  }
]

CodePudding user response:

You can separate the objects by center and accesses through use of &3 and &1 substitutions respectively while walking by the indices of the accesses array within a shift transformation such as

[
  {
    "operation": "shift",
    "spec": {
      "centre": {
        "*": {
          "accesses": {
            "*": {
              "@(2,name)": "&3[&1].&4", // go the tree up two levels and grab the "name"'s value while separating the objects by the indices of ***center*** and ***accesses*** arrays
              "n*": "&3[&1].&2", // filter "name" in this object by using "n*"(eg. a key starting with "n") since only name's key needs to be replaced, and go two levels up to grab the literal "accesses"
              "*": "&3[&1].&" // the rest of the attributes within the current object
            }
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": "" // get rid of the key names
      }
    }
  }
]

the demo on the site enter image description here

  • Related