Home > Blockchain >  JOLT JSON transform values from one-to-many to one-to-one
JOLT JSON transform values from one-to-many to one-to-one

Time:11-30

I'm trying to map one key to each value in array to a new array by using JOLT. Could someone please help give me a solution for this:

My JSON:

[
  {
    "person_id": "1",
    "resources": ["asd", "zxc"]
  },
  {
    "person_id": "2",
    "resources": ["ghj", "asd"]
  }
]

And my expected JSON:

[
  {
    "person_id": "1",
    "resource": "asd"
  },
  {
    "person_id": "1",
    "resource": "zxc"
  },
  {
    "person_id": "2",
    "resource": "ghj"
  },
  {
    "person_id": "2",
    "resource": "asd"
  }
]

I had tried this Jolt Specification

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "resources": {
          "*": {
            "@(2,person_id)": "[&].person_id",
            "@": "[&].resource"
          }
        }
      }
    }
  }
]

But no luck it always maps all values at the same index to 1 array.

CodePudding user response:

You can use two consecutive shift transformation specs by walking through the resources array within the first one such that

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*s": { // this tecnique stands for extracting by the replacement of the asterisk through use of &(2,1) below
          "*": {
            "@(2,person_id)": "[&3].&1.person_id", // to separate by indexes of the array to generate three level for three independent objects
            "@": "[&3].&1.&(2,1)"
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": ""
      }
    }
  }
]

the demo on the site enter image description here

CodePudding user response:

You can use this jolt spec:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*s": {
          "*": {
            "@(2,person_id)": "@(1).person_id",
            "@": "@(1).&(2,1)"
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": ""
    }
  }
]
  • Related