How to add a object to a Json in a Jolt Transform spec

Viewed 451

In nifi, I am trying to transform a JSON with a variable amount of keys, but will always have a "date" key. I would like to transform the Json and change the string value of the date into a json object. However I am not getting what I need. Which operation/spec can I use in order to accomplish the expected output. Input:

{
  "name": "val1",
  "date": "2021-05-19T00:53:20+00:00"
}

Spec:

[
  {
    "operation": "shift",
    "spec": {
      "@0": "wrapper"
    }
  }, {
    "operation": "default",
    "spec": {
      "wrapper": {
        "date": { "$date": "${date_attr}" }
      }
    }
  }
]

expected output

{
  "wrapper": {
    "name": "val1",
    "date": {"$date": "2021-05-19T00:53:20+00:00"}
  }
}

what I am getting

{
  "wrapper": {
    "name": "val1",
    "date": "2021-05-19T00:53:20+00:00"
  }
}
2 Answers

In case of default, if the key mentioned in the spec is missing in the input json, then its added or else no changes may happen. Here you are trying to push a node to a more level, which can be achieved by creating and assigning an temporary node.

\\ is an escape character.

[
  {
    "operation": "shift",
    "spec": {
      "date": "date1",
      "@0": "."
    }
  },
  {
    "operation": "remove",
    "spec": {
      "date": ""
    }
  }, {
    "operation": "shift",
    "spec": {
      "date1": "wrapper.date.\\$date",
      "@0": "wrapper"
    }
  }, {
    "operation": "remove",
    "spec": {
      "wrapper": {
        "date1": ""
      }
    }
  }
]

Only single step of shift transformation along with the escaping characters (\\) for $ operator would suffice to use such as

[
  {
    "operation": "shift",
    "spec": {
      "name": "wrapper.name",
      "date": { "@(1,date)": "wrapper.&.\\$date" }
    }
  }
]

where we're going one level up by using the first argument 1 in @(1,date) as been staying in the nested object

Edit : Considering that you only need to override the attribute date, and leave the others as they're without individually adding, use the following which again has only single step of shift transformation

[
  {
    "operation": "shift",
    "spec": {
      "*": "wrapper.&",
      "date": { "@(1,date)": "wrapper.&.\\$date" }
    }
  }
]
Related