cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

How to flatten hierarchial JSON structure?

ddangler
New Contributor III

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"
        }
      ]
    }
  }
]
3 REPLIES 3

tstack
Former Employee

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:

image

ddangler
New Contributor III

@tstack, Excellent! Thanks for detailed solution.

rohan
New Contributor

@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.