Mule- Dataweave 在现有有效负载中插入新的 json 字段

Mule- Dataweave to insert new json field in the existing payload

样本Json请求

{ "firstName": "George", "lastName": "Stephen" }

示例Json响应

{ "id": "123", "firstName" : "George", "lastName" : "Stephen" }

我想在响应 Json 中插入 id 值而不在 dataweave 中进行一对一映射(我已经有了在 dataweave 和 2 中进行一对一映射的工作解决方案)使用 groovy 零件)。

我原来的 JSON 请求很大而且有很多非必填字段,这就是我尝试这种方式的原因。

最简单的方法是在 dataweave 中使用 ++ 运算符,例如

%dw 1.0
%output application/json
---
payload ++  {id : "123"}

如果您必须更新子对象,您可以使用 mapObject。这将根据键名遍历每个 key.So,您可以使用 ++ 将字段添加到子对象。

希望对您有所帮助。

对于任何需要这个并且有一个 array 作为有效载荷的人,你可以这样做:

%dw 2.0
output application/json
---
payload map ((item, index) -> item ++ primary: true)

用您想要的 key-value 对替换“primary: true”。

DW Playground Screenshot Example

https://developer.mulesoft.com/learn/dataweave/ 非常适合玩弄数据编织代码。