I have the following json and I'm trying to extract certain elements of the phones array. I don't always get 2 elements, it could be 1,2, or 3.
{
"phones": [{
"id": 123,
"phoneType": "H",
"phoneNumber": "2125551212",
"countryCode": "1",
"isCellPhone": false,
"optInTexting": false
}, {
"id": 456,
"phoneType": "W",
"phoneNumber": "9197776262",
"countryCode": "1",
"isCellPhone": true,
"optInTexting": true
}
]
}
This is what I have with the output:
%output application/java
---
{
HOMEPH: payload.phones filter ($.phoneType == "H") map {HOMEPH:.phoneNumber},
WORKPH: payload.phones filter ($.phoneType == "W") map {WORKPH:$.phoneNumber}
}
The results I get from this:
HOMEPH: [{HOMEPH=2125551212}]
WORKPH: [{WORKPH=9197776262}]
What I want:
HOMEPH: "2125551212",
WORKPH: "9197776262"
Try following ways
%output application/java
---
{
HOMEPH: (payload.phones filter ($.phoneType == "H") map ($.phoneNumber)) [0],
WORKPH: (payload.phones filter ($.phoneType == "W") map ($.phoneNumber)) [0]
}
Or
%output application/java
%var phoneLookup = {(payload.phones map {
($.phoneType) : $
})}
---
{
HOMEPH: phoneLookup["H"].phoneNumber,
WORKPH: phoneLookup["W"].phoneNumber
}
Second option is more efficient as it iterates your payload once. Hope this helps.
Since you are using output as application/java
, you can try following:
%dw 1.0
%output application/java
---
{
(payload.phones filter ($.phoneType == "H") map {HOMEPH:$.phoneNumber}),
(payload.phones filter ($.phoneType == "W") map {WORKPH:$.phoneNumber})
}
You will get the output as below:
If you add Object to string transformer after Dataweave, you will get:
{HOMEPH=2125551212, WORKPH=9197776262}
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.