Search code examples
jsonapache-nifijolt

Combine known keys external to nested array as objects of that array


I have an input JSON that looks like this:

[
  {
    "some_key": "x",
    "foo_id": 123,
    "foo_name": "bar_1",
    "all_foo": [
      {
        "foo_id": 456,
        "foo_name": "bar_2"
      }
    ]
  }
]

The requirement is to collapse foo_id and foo_name (this is known ahead of time) as objects under all_foo, so that output is:

[
  {
    "some_key": "x",
    "all_foo": [
      {
        "foo_id": 123,
        "foo_name": "bar_1"
      },
      {
        "foo_id": 456,
        "foo_name": "bar_2"
      }
    ]
  }
]

Order on all_foo does not matter.

What I tried so far:

[
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "all_foo": {
        "*": "&",
        "&1": "[&1].&"
      }
    }
  }
]

Solution

  • You can use the following shift transformation spec

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "some_key": "&",
            "all_foo": {
              "@1,foo_name": "&1[0].foo_name",
              "@1,foo_id": "&1[0].foo_id",
              "*": "&1[]"
            }
          }
        }
      }
    ]
    

    or alternatively use the following one

    [
      {
        "operation": "shift",
        "spec": {
          "*": {
            "*": "&", // else case in which only "some_key" attribute is matched
            "foo_*": "all_foo.&", // all attributes those start with foo_
            "all_foo": {
              "*": "&1"
            }
          }
        }
      }
    ]
    

    where all key-value pairs are called from the same level of the tree