How To Transform Dynamic Json Using Dataweave - Mule 4
Dynamic Json Transformation example - Mule 4 Dataweave

How To Transform Dynamic Json Using Dataweave - Mule 4

There are various scenario where you have to transform a dynamic json during your Mulesoft transformation. In this post, I am going to talk about how to create a dataweave expression to find these dynamic tag and retrieve its value.

What is a Dynamic Json?

Dynamic json is a tag for which you do not know what key value will come in the response. It can be any label and normally comes as an array.

Example - As you can see below in the image; amdep1 and amdep2 is dynamic and it can have any label. You may not know it in advance.

No alt text provided for this image

So, how you will parse it. The solution is to use Pluck in dataweave and then convert array to object so that you can continue to loop.

See the complete example below

No alt text provided for this image

Sample code used below -

Input:

We need to get amdep1 and amdep2 value from below json

{
  "message": {
"response":{
"count": 200,
"employees": [
{
"department": "finance",
"Individual":
{
"depcode": {

"amdep1": {
"salescode":1,
"totalemployees": 234,
"label": "timesheet"
},

"amdep2": {

"salescode":1,
"totalemployees": 453,
"label": "compensation"
}
}
}
}
]
}
}
}        


Dataweave code -

%dw 2.0
output application/json
---

//pluck will get indidual value for the dynamic json; use depcode as parent tag to fetch value

payload.message.response.employees.Individual map ((key, index) ->
{(key.depcode)} pluck ((key1,index1) ->{
    
    salescode: key1.salescode,
    totalemployees:key1.totalemployees,
    label: key1.label
    
}
    
    
)   
)        

Final Output:

[
  [
    {
      "salescode": 1,
      "totalemployees": 234,
      "label": "timesheet"
    },
    {
      "salescode": 1,
      "totalemployees": 453,
      "label": "compensation"
    }
  ]
]        

Hope this small dataweave tricks helped you to get value from dynamic json. Please do use comments to let me know what other trick you follow to get dynamic json values.

Thank you and happy coding :)




To view or add a comment, sign in

More articles by Ravi Prakash Singh 🇮🇳

Others also viewed

Explore content categories