Search code examples
jsonjolt

Add Array Index using JOLT


I want to add a kind of line number or identifier with jolt for each array element.

Given Array:

[
  {
    "key1": "value1",
    "key2": "value2",
    "neyN": "valueN"
  },
  {
    "key1": "value1",
    "key2": "value2",
    "neyN": "valueN"
  }
]

Expected Result:

[
  {
    "key1": "value1",
    "key2": "value2",
    "neyN": "valueN",
    "id": 0
  },
  {
    "key1": "value1",
    "key2": "value2",
    "neyN": "valueN",
    "id": 1
  }
]

I tried now default, shift and more, but was not able to find a right solution. Can someone help me?

Thanks in advance Marcus


Solution

  • Spec 1 : Group the keys along with id field using index number.

    Spec 2 : Remove the index number key from the result array.

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "@": "&1",
            "$": "&1.id"
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": {
            "@": "[]"
          }
        }
      }
    ]