Akshay
Akshay

Reputation: 23

Jolt transform array into multiple Objects

I am trying to transform the below JSON:

Input:

{
  "steps": [
    {
      "end": "2023-01-27T09:19:29.849298Z",
      "id": "1",
      "start": "2023-01-27T09:18:24.59325Z",
      "name": "foo"
    },
    {
      "end": "2023-01-28T09:19:29.849298Z",
      "id": "2",
      "start": "2023-01-28T09:18:24.59325Z",
      "name": "bar"
    }
  ]
}

Output:

{
  "steps": [
    {
      "end": "2023-01-27T09:19:29.849298Z",
      "id": "1",
      "name": "foo",
      "start": "2023-01-27T09:18:24.59325Z"
    },
    {
      "end": "2023-01-28T09:19:29.849298Z",
      "id": "2",
      "name": "bar",
      "start": "2023-01-28T09:18:24.59325Z"
    }
  ],
  "date": [
    {
      "name": "startDate",
      "value": "2023-01-27T09:18:24.59325Z" //steps[0].start
    },
    {
      "name": "endDate",
      "value": "2023-01-27T09:19:29.849298Z" //steps[0].end
    }
  ]
}

I tried using the below spec:

[
  {
    "operation": "shift",
    "spec": {
      "steps": {
        "*": "steps[]",
        "0": {
          "#startDate": "date[0].name",
          "start": "date[0].value",
          "end": "date[1].value",
          "#endDate": "date[1].name"
        }
      }
    }
  }
]

But "*": "steps[]" only transforms the last element of the array steps. Please guide me as to what is wrong with the above spec, as I am new to jolt. Also, any pointers to the correct operations needed to achieve the above output will be greatly appreciated.

Upvotes: 1

Views: 300

Answers (2)

Barbaros Özhan
Barbaros Özhan

Reputation: 65105

One option is to conditionally pick by the existing(steps) array's indexes while walking through it such as

[
  {
    "operation": "shift",
    "spec": {
      "steps": {
        "@1": "",// derive the whole value from the upper level, eg. replicate it  
        "0": {// the first index
          "#startDate": "date[&1].name",
          "start": "date[&1].value"
        },
        "*": {// the other index(this case there's only one)
          "#endDate": "date[&1].name",// bring the value of the wrapper object'S index by using &1(going up one level the tree) 
          "end": "date[&1].value"
        }
      }
    }
  }
]

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

enter image description here

Upvotes: 0

Mohammadreza Khedri
Mohammadreza Khedri

Reputation: 2691

You can use this spec:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "@": "&1",
        "0": {
          "#startDate": "date[0].name",
          "start": "date[0].value",
          "#endDate": "date[1].name",
          "end": "date[1].value"
        }
      }
    }
  }
]

You can use @ to get the steps array and put it into the steps key with &1.

Upvotes: 1

Related Questions