Mule变换从有效载荷设置动态密钥

时间:2016-06-20 20:18:12

标签: mule anypoint-studio dataweave

我想从我的有效负载中的2个不同字段设置一个键值字典。我的第一个想法是使用转换组件并动态设置密钥,但此代码不起作用:

%dw 1.0
%output application/java
---
{
    payload.objectnumber: payload.objectid
}

我收到此错误:

Multiple markers at this line
- Invalid input "payload.", expected conditionalKeyValuePair,
   keyValuePair, enclosedExpr or objectEnd
- no viable alternative at input 'payload'
- no viable alternative at input '.'

关于如何使其发挥作用的任何想法?

输入:

[{
  objectnumber: 75,
  objectid: "abcdefgh"
}]

预期产出:

[{
  "abcdefgh": 75
}]

2 个答案:

答案 0 :(得分:2)

在括号(值)中放置一个变量来定义动态键。因此,您可以尝试以下代码:

%dw 1.0
%output application/json
---
payload map {
    ($.objectid): $.objectnumber
}

答案 1 :(得分:1)

尝试以下代码

    <dw:transform-message metadata:id="b968b3ec-ed0a-492d-bf32-bcfe0d20e9d0" doc:name="Transform Message">
        <dw:set-payload><![CDATA[%dw 1.0
       %output application/java
       %var objectId = payload.objectid
       ---
        objectId :payload.objectnumber
        ]]></dw:set-payload>
    </dw:transform-message>

Postman中的JSON输入:

 [  
   {  
  "objectnumber":75,
  "objectid":"abcdefgh"
   }
 ]