Mule dataweave从json数组中提取元素

时间:2017-08-02 14:31:38

标签: mule dataweave

我有以下json,我试图提取手机阵列的某些元素。我不总是得到2个元素,可能是1,2或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
    }
]

}

这就是我对输出的看法:

%output application/java
---
{
   HOMEPH:  payload.phones filter ($.phoneType == "H") map {HOMEPH:.phoneNumber},
   WORKPH:  payload.phones filter ($.phoneType == "W") map {WORKPH:$.phoneNumber}
}

我从中得到的结果:

HOMEPH: [{HOMEPH=2125551212}]
WORKPH: [{WORKPH=9197776262}]

我想要的是什么:

HOMEPH: "2125551212",
WORKPH: "9197776262"

2 个答案:

答案 0 :(得分:2)

尝试以下方式

%output application/java
---
{
   HOMEPH:  (payload.phones filter ($.phoneType == "H") map ($.phoneNumber)) [0],
   WORKPH:  (payload.phones filter ($.phoneType == "W") map ($.phoneNumber)) [0]
}

或者

%output application/java
%var phoneLookup = {(payload.phones map { 
    ($.phoneType) : $
})}
---
{
   HOMEPH:  phoneLookup["H"].phoneNumber,
   WORKPH:  phoneLookup["W"].phoneNumber
}

第二个选项更有效,因为它会迭代您的有效负载一次。 希望这会有所帮助。

答案 1 :(得分:1)

由于您将输出用作application/java,因此您可以尝试以下操作:

%dw 1.0
%output application/java
---
{
    (payload.phones filter ($.phoneType == "H") map {HOMEPH:$.phoneNumber}),
    (payload.phones filter ($.phoneType == "W") map {WORKPH:$.phoneNumber})
}

您将获得如下输出: enter image description here

如果在Dataweave之后将Object添加到字符串转换器,您将获得:

{HOMEPH=2125551212, WORKPH=9197776262}