Vikram Saini
Vikram Saini

Reputation: 2769

loop inside transform in mule

i am new to mule and i have to convert json to xml.here is the transform output code

%dw 1.0
%input payload application/json
%output application/xml
---
{( 
items:
{


    Id:payload.abc.productid,
    ProductPrice:payload.abc.price,
    Name:payload.abc.productname

}

)}

Here is the schema against which i am testing

{
    "abc":
    {
    "productid":"4",
    "productname":"Shampoo",
    "price":["1000","2000","3000"]
    }   

    }

It generates correct xml in case i send only one item in array price but in case i send multiple elements it gives me this error

Cannot coerce a :array to a :object.

I know i should loop inside it but i do not know how to make it possible

Please guide!

Upvotes: 0

Views: 1207

Answers (2)

a.cayzer
a.cayzer

Reputation: 289

You could use the following:

{
items: {
    (payload map ((payload01 , indexOfPayload01) -> {
        item: {
            Id: payload01.productid,
            Name: payload01.productname,
            (payload01.price map ((price , indexOfPrice) -> {
                price: price
            }))
        }
    }))
}
}

I have removed the "abc" from the incoming data so the format is as:

[
{
"productid":"4",
"productname":"Shampoo",
"price":["1000","2000","3000"]
},
 {
"productid":"4",
"productname":"not shampoo",
"price":["1000","2000","3000"]
}
]

Let me know if the abc needs to be there, but I hope this helps

Upvotes: 3

Yevgeniy
Yevgeniy

Reputation: 2694

you can use the map keyword to iterate over arrays in Dataweave. Take a look at the documentation here.

Upvotes: 1

Related Questions