0

i have this input

[{
    "omsNo": "S001",
    "recipient": [{
            "name": "name1",
            "address": "address1"
        },
        {
            "name": "name2",
            "address": "address2"
        }
    ]
}]

may i know how to get this result using dataweave

[{"omsNo":"S001","name":"name1","address":"address1"},{"omsNo":"S001","name":"name2","address":"address2"}]

2 Answers 2

3

Input

[{
    "omsNo": "S001",
    "recipient": [{
            "name": "name1",
            "address": "address1"
        },
        {
            "name": "name2",
            "address": "address2"
        }
    ]
}]

Script

%dw 2.0
output application/json
---
flatten(payload map ((item, index) -> 
   (item.recipient map ((itemRecipient, indexRecipient)  -> (
        ({omsNo: item.omsNo} ++ itemRecipient) 
   ))
)))

Output

[
  {
    "omsNo": "S001",
    "name": "name1",
    "address": "address1"
  },
  {
    "omsNo": "S001",
    "name": "name2",
    "address": "address2"
  }
]
Sign up to request clarification or add additional context in comments.

Comments

0

Here's an alternative solution:

%dw 2.0
output application/json
---
payload.recipient[0] map (v0,k0) ->
{
    omsNo:payload.omsNo[0],
    name:v0.name,
    address:v0.address
}

4 Comments

It's working but I think the proper selector should be payload[0].recipient and payload[0].omsNo
Ok @Jorge Garcia. Do you mind explaining why the selector you mentioned is more appropriate. 😊
Sure, sorry. If we look at the original input, the payload is an array with one object inside, so first, you select the first object of the array and then ask for the recipient field of that object. That selection is more direct. Your code is also working because DataWeave selectors automatically generate an array when any of the items in the selector is an array, and then collect the leaves, but you may get inconsistent behaviors if there are more objects in the arrays or you have more levels of arrays.
Thanks @JorgeGarcia, appreciate the effort to explain !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.