Balaji211
Balaji211

Reputation: 307

Jolt Transform JSON Spec

I need to transform below Input JSON to output JSON and not sure about how to write spec for that. Need to re-position one field ("homePage") as a root element. Any help or suggestion would be appreciated.

Input JSON :

[{
    "uuid": "cac40601-ffc9-4fd0-c5a1-772ac65f0587",
    "pageId": 123456,    
    "page": {
      "indexable": true,
      "rootLevel": false,
      "homePage": false      
    }
}]

Output JSON :

[{
    "uuid": "cac40601-ffc9-4fd0-c5a1-772ac65f0587",
    "pageId": 123456,
    "homePage": false,  
    "page": {
      "indexable": true,
      "rootLevel": false           
    }
}]

Upvotes: 0

Views: 666

Answers (1)

kasptom
kasptom

Reputation: 2458

This Jolt Spec should work for you. Tested with https://jolt-demo.appspot.com/

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "uuid": "[&1].uuid",
        "pageId": "[&1].pageId",
        "page": {
          "indexable": "[&2].page.indexable",
          "rootLevel": "[&2].page.rootLevel",
          "homePage": "[&2].homePage"
        }
      }
    }
  }
]

input:

{
  "uuid" : "cac40601-ffc9-4fd0-c5a1-772ac65f0587",
  "pageId" : 123456,
  "page" : {
    "indexable" : true,
    "rootLevel" : false
  },
  "homePage" : false
}

output:

[ {
  "uuid" : "cac40601-ffc9-4fd0-c5a1-772ac65f0587",
  "pageId" : 123456,
  "page" : {
    "indexable" : true,
    "rootLevel" : false
  },
  "homePage" : false
} ]

Explanation:

From the javadoc

& Path lookup

As Shiftr processes data and walks down the spec, it maintains a data structure describing the path it has walked. The & wildcard can access data from that path in a 0 major, upward oriented way. Example:

{
   "foo" : {
       "bar": {
         "baz":  // &0 = baz, &1 = bar, &2 = foo
      }
   }
}

Next thing: How to wrap the output object into the array? A good example can be found in this post.

So, in our case:

  • "[&1].uuid" says:

Place the uuid value in the object inside the array. The index of the array is indicated by the &1 wildcard. For uuid it will be the index of the array, where the object with uuid key is placed in the original json.

  • Next, [&2] is similar to [&1]. However, looking at the "indexable" key, it is one level deeper in the input json. Thats why instead of [&1] we used [&2] (have a look again at the foo-bar example from the docs).

Upvotes: 3

Related Questions