我需要使用DataWeave(3.0(将新属性(简单和嵌套(添加到现有的JSON有效载荷中。我要在下面发布示例有效载荷:
{
"entities": [
{
"ID": "ABC",
"sourceEnt": {
"entityId": "100A",
"entity": {
"Code": "AB",
"Idf1": "1pwe",
"Idf2": null,
"OrgAddr": [
{
"OrgAddrIdf1": "1pwe1",
"Rank": 1,
"Label": "One",
"MainAddr": {
"AddrLine1": "abc",
"PoBox": 123,
"DistrictCode": null
}
},
{
"OrgAddrIdf1": "1pwe2",
"Rank": 2,
"Label": "Two",
"MainAddr": {
"AddrLine1": "xyz",
"PoBox": 456,
"DistrictCode": null
}
}
]
}
}
}
]
}
在上述有效载荷中,我需要在orgaddr.mainaddr上添加一个新属性(" statecode":" null"(,以及一个新属性称为" flag":"是",orgaddr之后。我可以在末尾添加新的"标志"属性,但是如何修改嵌套属性(orgaddr(。请注意,我需要将简单和嵌套的属性添加在一起。
非常间接的用例。我能够通过创建两个启动助手功能来解决它。
%dw 2.0
output application/json
/**
* Updates the value of the specified field If the field doesn't exits it will be inserted at the bottom. Use this function with `with`. The with will receive the old value
*/
fun update(objectValue: Object, fieldName: String) =
(newValueProvider: (oldValue: Any, index: Number) -> Any) -> do {
if(objectValue[fieldName]?)
objectValue mapObject ((value, key, index) ->
if(key ~= fieldName)
{(key): newValueProvider(value, index)}
else
{(key): value}
)
else
objectValue ++ {(fieldName): newValueProvider(null, 0)}
}
/**
* Updates the value at the specified index. If the index is bigger than the size it will be appended. Use this function with `with`. The with will receive the old value
*/
fun update(arrayValue: Array, indexToUpdate: Number) =
(newValueProvider: (oldValue: Any, index: Number) -> Any) -> do {
if(arrayValue[indexToUpdate]?)
arrayValue map ((value, index) ->
if(index == indexToUpdate)
newValueProvider(value, index)
else
value
)
else
arrayValue << newValueProvider(null, 0)
}
---
payload update "entities" with (
$ update 0 with (
$ update "sourceEnt" with (
$ update "entity" with (
$ update "OrgAddr" with (
$ map ((item, index) -> item update "MainAddr" with ($ ++ {"StateCode": null}) )
) ++ {
"Flag" : "yes"
}
)
)
)
)
两个更新功能可以帮助我穿越对象并更新需要更新或修改的树结构的各个部分。
dataWeave的2.3版本
答案payload update {
case entity at.entities[0].sourceEnt.entity -> do {
entity update {
case addresses at .OrgAddr -> do {
addresses map ((addr, index) -> addr update {
case .MainAddr.StateCode! -> null
})
}
case .Flag! -> "Yes"
}
}
}
您可以尝试以下方法:
%dw 1.0
%output application/json
%var pay=flatten payload.entities.sourceEnt.entity.OrgAddr
---
{(pay)} mapObject {
($$):$ when ($$ as :string) != "MainAddr" otherwise {"StateCode": "null"} ++ $
}