Search code examples
jsonapache-nifijolt

Jolt transform array of documents. Move parent attributes to a child


I have an array of json objects that I need to transform using JOLT

Input

[
  {
    "name": "john",
    "age": 12
  },
  {
    "name": "tom",
    "age": 12
  }
]

Expected Output

[
  {
    "details": {
      "name": "john",
      "age": 12
    }
  },
  {
    "details": {
      "name": "tom",
      "age": 12
    }
  }
]

I currently have the following spec:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "@": "details.&"
      }
    }
  }
]

which results in the entire array of objects being wrapped in "details" as well as each element of the array being assigned it index as its key.

{
  "details" : {
    "0" : {
      "name" : "john",
      "Age" : 12
    },
    "1" : {
      "name" : "tom",
      "Age" : 12
    }
  }
}

Solution

  • You can revert the order as "&.details" in order to distinguish the objects by uncommon values(1,2,...) rather than the common literal details such as

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "@": "&.details"
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": ""
        }
      }
    ]
    

    then, get rid of the object labels within the last transformation spec

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

    enter image description here