user3868764
user3868764

Reputation: 21

How to do the jolt transformation for a list of json object

My Input is as below:

[
  {
    "Id": "327703",
    "Caption": "TEST>> photo 1",
    "Url": "http://bob.com/0001/327703/photo.jpg"
  },
  {
    "Id": "327704",
    "Caption": "TEST>> photo 2",
    "Url": "http://bob.com/0001/327704/photo.jpg"
  }
]

and the expected output is:

{
    "327703": {
        "Caption": "TEST>> photo 1",
        "Url": "http://bob.com/0001/327703/photo.jpg"
    },
    "327704": {
        "Caption": "TEST>> photo 2",
        "Url": "http://bob.com/0001/327704/photo.jpg"
    }
}

Please help me this and please suggest a good tutorial to get the fundamentals of all wildcards in JOLT.

Upvotes: 0

Views: 1655

Answers (1)

kasptom
kasptom

Reputation: 2458

This spec should work for you:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "Id": null,
        "*": "@(1,Id).&"
      }
    }
  }
]

The resources that I've learned from are:

For this transformation have a look at shift docs - especially:


Explanation of the above:

  1. Outermost part matches every element of our list:
"*" : { 
... 
}
  1. The inside of the object:
    "Id": null

Says

For every "Id" key inside each element of the array (found during the 1st step): put the value under the null key - remove the "Id" key and its value from the element of the list.

The second part:

   "*": "@(1,Id).&"

Says:

match all other keys within the list element and place them under the "@(1,Id).&" key.

What does "@(1,Id).&" mean? Looking at the docs linked above we can translate (paraphrasing the advanced @ wildcard docs):

  • "@(1,Id)" to:

Go up one level from here and look for the value under the "Id" key. Use the value at that key (as our new key).

"@(1,Id)" becomes "327703" for the 0th element of the array.

... ok but we do not want to place values from "Caption" and "Url" right under the "327703". If we did, our object would look like this:

{
  "327703" : [ "TEST>> photo 1", "http://bob.com/0001/327703/photo.jpg" ],
  ...
}

We want to place "Caption" under the "Caption". Here the & wildcard comes in handy (look at the docs linked above). When "*" wildcard matches:

  • "Candy"- the value under the "Candy" key will be placed in the output's "327703"."Candy" key
  • "Url"- the value under the "Url" key will be placed in the output's "327703"."Url" key

etc.

Upvotes: 1

Related Questions