Search code examples
jsonapache-nifijolt

Assign a key as key to all elements of a sibling array


I have an input JSON like this:

{
  "some_key": "x",
  "another_key": "y",
  "foo_id": 123,
  "all_foo": [
    {
      "foo_name": "bar1"
    },
    {
      "foo_name": "bar2"
    }
  ]
}

I'm looking for an output JSON like this:

{
  "some_key": "x",
  "another_key": "y",
  "all_foo": [
    {
      "foo_id": 123,
      "foo_name": "bar1"
    },
    {
      "foo_id": 123,
      "foo_name": "bar2"
    }
  ]
}

What I tried so far:

[
  {
    "operation": "shift",
    "spec": {
      "all_foo": {
        "*": {
          "*": "[&1].&",
          "@(2,foo_id)": "[&1].foo_id"
        }
      }
    }
  }
]

This works for all_foo. But I'm unable to keep some_key and another_key.


Solution

  • You can use the following shift transformation spec

    [
      {
        "operation": "shift",
        "spec": {
          "some*|ano*": "&", // "some_key" or(pipe) "another_key"(* is complementary, eg. key names start with "some" or "ano")
          "all_foo": {
            "*": {
              "@2,foo_id": "&2[&1].foo_id",
              "*": "&2[&1].&"
            }
          }
        }
      }
    ]
    

    where

    • "some*|ano*": "&" represents replication of the outer attributes except for foo_id

    • &2s represent going two levels up the tree, and grabbing the literal all_foo in order to form an array called all_foo