How to flatten hierarchial JSON structure?

Hi Forum,

I have hierarchical JSON structure coming as input and need to flatten(and transformation) the document as output. Below is the simple example showing input and output structure. I tried doing this with Mapper, Strcuture and JSON Splitter snaps but could not achieve it. Anyone know how to solve this?

Input document structure:

[
  {
    "entity": {
      "results": [
        {
          "id": 453721,
          "custom_fields": [
            {
              "id": 11111,
              "value": "AAAA"
            },
            {
              "id": 22222,
              "value": "BBBB"
            },
            {
              "id": 33333,
              "value": "CCCC"
            }
          ]
        }
      ]
    }
  }
]

Desired Output Document structure:

[
  {
    "entity": {
      "results": [
        {
          "id": 453721,
          "11111" : "AAAA",
          "22222" : "BBBB"
        }
      ]
    }
  }
]

The “extend()” method on objects can be used to construct new objects in various ways. For this case, you can create a list of key/value pairs and then extend an existing to create a new object. The pairs can be created using the ‘map()’ method on arrays to iterate over each element and construct the pair. Altogether, it would look like this:

{id: $id}.extend($.custom_fields.map(elem => [elem.id, elem.value]))

That should take care of transforming each element in the result array. You can then use the ‘Mapping Root’ feature in the mapper to transform each element in the ‘results’ array. Here is the Mapper configuration that should work:

4 Likes

@tstack, Excellent! Thanks for detailed solution.

@tstack instead of mapping the key/value pairs like {id:$id}, is there a way we can dynamically fetch all the key/value pairs and then extend them with custom fields?

Any help is appreciated.