How to extract the desired output from this json?

Viewed 31

json Input:


[ { "brand": "mobile", "qty": 245 }, { "brand": "tablet", "qty": 1202 }, { "brand": "xbox", "qty": 6031 } ]

Desired json output:


{ "mobile" : 245, "tablet" : 1202, "xbox" : 6031 }

2 Answers

One possible solution:

%dw 2.0
output application/json  
---
payload reduce ((item, accumulator = {}) -> accumulator ++ 
    {(item.brand): item.qty}
)

This option uses the reduce function that accumulate the desired key:value pairs into an object. You can learn more about it in the DataWeave Interactive Tutorial (section 7.5-reduce)

You could also use the object constructor after mapping the array as StackOverflowed proposed in his solution.

This has more info on Dynamic elements using the object constructor https://docs.mulesoft.com/dataweave/2.4/dataweave-types#dynamic_elements

An alternate solution :

%dw 2.0
output application/json  
---
{
  (payload map 
    ($.brand): $.qty // Iterate over and map brand key's value with qty key's value
  )
} // to enclose output within an object
Related