Marcus K
Marcus K

Reputation: 15

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

Upvotes: 1

Views: 1057

Answers (2)

Barbaros Özhan
Barbaros Özhan

Reputation: 65393

All that you need is to bring the objects' indexes through use of $ wildcard while keeping the current values, and do all in arraywise manner. Only the following single spec will accomplish this :

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

the demo on the site http://jolt-demo.appspot.com/ is :

enter image description here

Upvotes: 1

Jagadesh
Jagadesh

Reputation: 2116

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": {
      "*": {
        "@": "[]"
      }
    }
  }
]

Upvotes: 3

Related Questions