soumya
soumya

Reputation: 3

DataWeave move child key value into parent key

I have the following JSON as an input:

[
    {
        "abc: {
            "s": "123"
        },
        "pqr": {
            "s": "234"
        },
        "xyz": {
            "s": "345"
        }
    },
     {
        "abc: {
            "s": "456"
        },
        "pqr": {
            "s": "567"
        }
    }
]

My expected output is:

[
    {
        "abc: "123",
        "pqr": "234",
        "xyz": "345"
    },
     {
        "abc: "456",
        "pqr": "567",
        "xyz": null
    }
]

How can I achieve this in mule 4? Please suggest.

Note: The JSON object keys are dynamic. Here in the sample input, 3 keys are seen. But, as per input payload from other APIs, there can be more keys i.e. abc,def,pqr,mno,xyz etc.

Upvotes: 0

Views: 292

Answers (1)

Harshank Bansal
Harshank Bansal

Reputation: 3262

You can use mapObject to update each element of your array dynamically. If the JSON with the main value always has single field, you can get it using its index [0].

For making sure to get all the keys in each object you will have to fetch all the keys initially and write the script around that.

%dw 2.0
var allFields = payload flatMap keysOf($) distinctBy ($)
output application/json  
---
payload map ((nestedJson) -> 
    allFields reduce ((field, acc = {}) -> {
        (acc),
        (field): (nestedJson[field])[0]
    })
)

Upvotes: 1

Related Questions