Home > Mobile >  How do I write a jolt transform spec to iterate through a loop?
How do I write a jolt transform spec to iterate through a loop?

Time:09-08

I have the following

Input JSON :

{
  "a": [
    [
      "a1"
    ],
    [
      "a2"
    ]
  ],
  "b": [
    [
      "b1",
      "b2"
    ],
    [
      "b3",
      "b4"
    ]
  ]
}

I want to use jolt transform to output it like this:

Output JSON:

[
  {
    "a": "a1",
    "b": "b1"
  },
  {
    "a": "a1",
    "b": "b2"
  },
  {
    "a": "a2",
    "b": "b3"
  },
  {
    "a": "a2",
    "b": "b4"
  }
]

I use combination of shift and cardinality but can't seem to get it to iterate through correctly:

[
  {
    "operation": "shift",
    "spec": {
      "*": "&"
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": "[&].&1"
      }
    }
  },
  {
    "operation": "cardinality",
    "spec": {
      "*": {
        "*": "ONE"
      }
    }
  }
]

What do I need to change to that jolt transform spec to get it to work?

CodePudding user response:

You can walk by the indexes of the array "b" while picking values from the array "a" as well such as

[
  {
    // partition by indexes of array "a"&"b" while strolling through the array "b"
    "operation": "shift",
    "spec": {
      "b": {
        "*": {
          "@(2,a)": {
            "*": "&.&1.a"
          },
          "*": "&1.&.&2"
        }
      }
    }
  },
  {
    // get rid of object labels
    "operation": "shift",
    "spec": {
      "*": {
        "*": ""
      }
    }
  },
  {
    // get rid of square brackets wrapping up the values of the attributes "a"
    "operation": "cardinality",
    "spec": {
      "*": {
        "a": "ONE"
      }
    }
  },
  {
    // order the attributes by the key names
    "operation": "sort"
  }
]

the demo on the site enter image description here

  • Related