全部。 我正在尝试使用条件更改json中数组元素的字段值:如果“ field1”的值等于“ value1”,则将字段“ changethisfield”的值更改为“ new_value”。 当前有效载荷:
{
"message": [
{
"field1": "value1",
"field2": "value2",
"changethisfield": ""
},
{
"field1": "value3",
"field2": "value4",
"changethisfield": ""
}
]
}
Dataweave代码:
%dw 2.0
output application/json
var itemValue = payload.message map (item) -> {
(item mapObject (value, key, index) -> {
((key): value) if (key as String != 'changethisfield'),
(changethisfield: "new_value") if (key as String == 'changethisfield')
})
}
---
{
"message": {
item: itemValue
}
}
但是此代码更改了数组所有元素的值(当前输出):
{
"message": {
"item": [
{
"field1": "value1",
"field2": "value2",
"changethisfield": "new_value"
},
{
"field1": "value3",
"field2": "value4",
"changethisfield": "new_value"
}
]
}
}
所需的输出(只有“ field1”包含“ value1”的“ changethisfield”项目的值应更改为“ new_value”):
{
"message": {
"item": [
{
"field1": "value1",
"field2": "value2",
"changethisfield": "new_value"
},
{
"field1": "value3",
"field2": "value4",
"changethisfield": ""
}
]
}
}
请帮助您理解如何在数组元素中创建条件并解决此任务。谢谢!
答案 0 :(得分:4)
这应该有效:
%dw 2.0
output application/dw
var data = {
"message": [
{
"field1": "value1",
"field2": "value2",
"changethisfield": ""
},
{
"field1": "value3",
"field2": "value4",
"changethisfield": ""
}
]
}
---
message: data.message map {
($ - "changethisfield"),
changethisfield: if ($.field1 == "value1") "new_value" else $.changethisfield
}
答案 1 :(得分:4)
希望添加您也可以使用update
函数,而不是删除将字段手动添加到对象的方法。这也可以将数组中的每个项目都更改为特定值,但是由于您有条件,因此必须在地图内执行。
比较的问题是,仅当键是特定字符串时,才将比较作为对象级别进行。您无需检查field1是否具有特定值。
%dw 2.0
output application/json
import * from dw::util::Values
var inputData = {
"message": [
{
"field1": "value1",
"field2": "value2",
"changethisfield": ""
},
{
"field1": "value3",
"field2": "value4",
"changethisfield": ""
}
]
}
---
{
message: inputData.message map ((item, index) -> (
if (item.field1 == "value1") (
item update "changethisfield" with "newValue"
) else (
item
)
))
}