简体   繁体   中英

Array of objects to a single object containing all said objects Dataweave

I am trying to transform the below Array of Objects input:

[
 {
    "Id": "3",
    "Code": "4190484",
    "Expense": "Huge Expense "   
 },
 {
    "Id": "4",
    "Code": "271",
    "Expense": "Big Expense"   
 },
 {
    "Id": "3",
    "Code": "433",
    "Expense": "No Expense"   
 } 
]

to this Output of a single object:

{
    "Id": "3",
    "Code": "4190484",
    "Expense": "Huge Expense ",
    "Id": "4",
    "Code": "271",
    "Expense": "Big Expense",
    "Id": "3",
    "Code": "433",
    "Expense": "No Expense"
}

How would you accomplish this in Dataweave?

You can also use the dynamic elements feature of the language:

%dw 2.0
output application/json
---
{(payload)}

Like @aled explained in his answer, you should not be using duplicate keys in JSON.

You can use the reduce() function but be warned that using duplicate keys in JSON is implementation dependent. I think it is a bad design to use duplicate keys in JSON. It might lead to unexpected behaviors. Some implementations might ignore the duplicates. For example DataWeave will return only one Id of the resulting object with payload.Id .

If even after what I mentioned you still want to go ahead it this is an example:

%dw 2.0
output application/json
---
// I don't recommend to use duplicate keys
payload reduce  ((item, acc = {}) -> acc ++ item)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM