Array to flat mapping in mule based on condition

I am trying to map the response from a third-party call to another structure using the DataMapper transform inside the Mule.

From a third party, we get an array of elements (by the way), and I want to map one element in the array to an object (JSON). I get the identifier for the item in the request, which is available as an input argument.

My question is, how can I match element fields based on identifier?

XML response example

<account> <accountNumber>1234567</accountNumber> <books> <book> <id>1</id> <title>Sample title1</title> <availableFrom>21-03-16</availableFrom> </book> <book> <id>2</id> <title>Sample title2</title> <availableFrom>21-03-16</availableFrom> </book> <book> <id>3</id> <title>Sample title3</title> <availableFrom>21-03-16</availableFrom> </book> </books> </account> 

Need to become:

 { "person": { "accountNumber": 1234567, "selectedBook": { "id": 1, "title": "Sample title1" }, "otherBooks": [ { "id": 2, "title": "Sample title2" }, { "id": 3, "title": "Sample title3" } ] } } 

The ID of the selected book is stored in inputArgument.bookId .

I can complete the mapping using the xpath rule for each of the fields, however I need to hardcode the bookId into xpath. Instead, I need to be able to substitute the actual identifier for the provided (and available in inputArgument).

xpath for header

 /account/books/book[child::id=1]/title 

I tried adding MEL to replace id and other other fixes, but nothing works. Is there any way to replace the bookId field.

Note. Due to client restrictions, I cannot use DataWeave.

+5
source share
2 answers

Using dataweave, you can do something like this.

 <dw:transform-message metadata:id="0ce877a9-29ed-401b-bd54-b90d42a1609f" doc:name="Transform Message"> <dw:set-payload><![CDATA[%dw 1.0 %var bookId = "1" %var account = payload.account %var books = payload.account.books %output application/json --- { person : { accountNumber: account.accountNumber, selectedBooks: (books.*book map { id : $.id, title: $.title } filter $.id == bookId)[0], otherBooks: books.*book map { id : $.id, title: $.title } filter $.id != bookId } }]]></dw:set-payload> </dw:transform-message> 
0
source

You must use the Group By operation to convert your XML file to the required JSON format. you can do something like this:

DataWeave conversion example:

 %dw 1.0 %output application/dw --- classrooms: payload.school.teachers groupBy $.subject mapObject ((teacherGroup, subject) -> { class: { name: subject, teachers: { (teacherGroup map { teacher:{ name: $.name, lastName: $.lastName } }) }, attendees: { (payload.school.students filter ($.*hobby contains subject) map { attendee: { name: $.name, lastName: $.lastName } }) } } }) 
-1
source

Source: https://habr.com/ru/post/1245517/


All Articles