Jolt spec to transform an array of elements into objects with ids

703 Views Asked by At

Jolt is new to me and I have been struggling with this issue till the point where I created this post.

I want to turn this:

{
    "Properties": [{
        "Id": "property1",
        "Values": ["randomValue1", "randomValue2"]
    }, {
        "Id": "property2",
        "Values": "randomValue3"
    }, {
        "Id": "property3",
        "Values": "randomValue4"
    }]
}

into this

{
    "Properties": [{
        "Id": "property1",
        "Values": "randomValue1"
    },{
        "Id": "property1",
        "Values": "randomValue2"
    }, {
        "Id": "property2",
        "Values": "randomValue3"
    }, {
        "Id": "property3",
        "Values": "randomValue4"
    }]
}

The values for each property can be 1 value or an array of an unknown amount of values.

I changed the following json into what is seen in the first json already:

{
    "Properties": {
        "property1": ["randomValue1", "randomValue1"],
        "property2": ["randomValue3"],
        "property3": ["randomValue4"]
    }
}

Spec:

[{
    "operation": "shift",
    "spec": {
        "Properties": {
            "*": {
                "*": "Properties[#2].Values",
                "$": "Properties[#2].Id"
            }
        }
    }
}]

Property names on RHS are generic and the number of values for a property can differ as well. Thank you in advanced for taking the time to assist me.

1

There are 1 best solutions below

0
On

check if this helps:

[
  {
    "operation": "cardinality",
    "spec": {
      "Properties": {
        "*": {
          // normalize values to always be a list
          "Values": "MANY"
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "Properties": {
        "*": {
          "Values": {
            "*": {
              // create arrays with values and ids
              "@": "Values",
              "@(2,Id)": "Id"
            }
          }
        }
      }
    }
  },
  {
    "operation": "shift",
    "spec": {
      "Values": {
        "*": {
          // create the final list joining ids and values at the indexes you want
          "@": "Properties[&1].Values",
          "@(2,Id[#1])": "Properties[&1].Id"
        }
      }
    }
  }
]