使用dataweave创建json数组

时间:2017-05-18 14:07:28

标签: mule dataweave

如果我有像这样的xml ......

<Root>
  <Authority>Water</Authority>
  <Sanctions>
    <Sanction>
      <SanctionCode>11</SanctionCode>
      <SanctionDesc>First Sanction</SanctionDesc>
    </Sanction>
    <Sanction>
      <SanctionCode>11</SanctionCode>
      <SanctionDesc>Second Sanction</SanctionDesc>
    </Sanction>          
  </Sanctions>
</Root>

使用DataWeave如何仅使用SanctionDesc创建Santions的json数组?

我试过了,但这不对......

%dw 1.0
%output application/json
---
records: payload.Root map {
   Authority: $.Authority,
   sanctions: $.Sanctions.Sanction map [$.SanctionDesc]
}

我希望我的输出看起来像这样......

{
    "records": [{
        "Authority": "Water",
        "sanctions": ["First Sanction", "Second Sanction"]
    }]
}

2 个答案:

答案 0 :(得分:3)

试试这个

%dw 1.0
%output application/json
---
records: {
   Authority: payload.Root.Authority,
   sanctions: payload.Root.Sanctions..SanctionDesc
}

或者

%dw 1.0
%output application/json
---
records: {
   Authority: payload.Root.Authority,
   sanctions: payload.Root.Sanctions.*Sanction map $.SanctionDesc
}

希望这有帮助。

答案 1 :(得分:0)

从输入有效负载中挑选和选择元素时,解决地图运算符的问题是关键。 Map运算符遍历左侧的所有数组元素,我们可以从右侧选择值,从Mulesoft门户获取示例

%dw 1.0

%输出应用程序/ json

用户:[&#34; john&#34;,&#34; peter&#34;,&#34; matt&#34;] map((firstName,position) - &gt; position ++&#34; :&#34; ++ upper firstName)

输出: {   &#34;用户&#34;:[     &#34; 0:JOHN&#34 ;,     &#34; 1:PETER&#34 ;,     &#34; 2:MATT&#34;   ] }

请参阅以下链接: https://docs.mulesoft.com/mule-user-guide/v/3.8/dataweave-operators#map