thedrone
thedrone

Reputation: 23

Jolt - How to convert two arrays to key value and keep other singles properties

I have a JSON that contains two arrays that I need to convert to key / value pairs. These keys on the array are dynamic and can change.

For that I'm trying to create a Jolt spec to convert my input data into the format below.

JSON Input:

{
  "data": [
    {
      "property1": "AA",
      "property2": "BB",
      "keys": [
        "key1",
        "key2",
        "key3"
      ],
      "values": [
        "value1",
        "value2",
        "value3"
      ]
    },
    {
      "property1": "CC",
      "property2": "DD",
      "keys": [
        "key4",
        "key5"
      ],
      "values": [
        "value4",
        "value5"
      ]
    }
  ]
}

Desired output:

[
  {
    "property1": "AA",
    "property2": "BB",
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
  },
  {
    "property1": "CC",
    "property2": "DD",
    "key4": "value4",
    "key5": "value5"
  }
]

My spec:

[
  {
    "operation": "shift",
    "spec": {
      "data": {
        "*": {
          "values": {
            "*": {
              "@": "[&3].@(3,keys[&1])"
            }
          }
        }
      }
    }
 }
]

My spec output:

[
  {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
  },
  {
    "key4": "value4",
    "key5": "value5"
  }
]

But I'm not able to correctly include the simple properties (property1 and property2) as in the desired output.

Thanks in advance

Upvotes: 2

Views: 1001

Answers (1)

Arun Sai
Arun Sai

Reputation: 1972

[
  {
    "operation": "shift",
    "spec": {
      "data": {
        "*": {
          "property1": "[&1].property1",
          "property2": "[&1].property2",
          "values": {
            "*": {
              "@": "[&3].@(3,keys[&1])"
            }
          }
        }
      }
    }
 }
]

Really you grouped the dynamic elements into key-value pairs greatly, but you just missed the position mapping of property1 and property2 fields into output.

Upvotes: 1

Related Questions