我的样本输入有效载荷如下:
{
"entities": [
{
"Id": "ab5fdd89e123",
"target": {
"Data": {
"attributes": {
"Name": [],
"Address": [
{
"value": {
"AddType": [{"value": "MAIN"}],
"Flag": [{"value": true }]
}
}]}}}}]}
我需要将值为true的名为Flag(target.Data.attributes.Address.value.Flag)的属性替换为“ PrimaryFlag”。我还需要在名为“ Code”的属性之后添加一个新属性,其值为null。所需的输出应如下所示:
{
"entities": [
{
"Id": "ab5fdd89e123",
"target": {
"Data": {
"attributes": {
"Name": [],
"Address": [
{
"value": {
"AddType": [{"value": "MAIN"}],
"PrimaryFlag": [{"value": true }],
"Code": [{"value": null}]
}
}]}}}}]}
我正在运行Mule 3.9,并且在dataweave 1.0上
尝试一下-它包含注释:
%dw 1.0
%output application/dw
%var data = {
"entities": [
{
"Id": "ab5fdd89e123",
"target": {
"Data": {
"attributes": {
"Name": [],
"Address": [
{
"value": {
"AddType": [
{
"value": "MAIN"
}
],
"Flag": [
{
"value": true
}
]
}
}
]
}
}
}
}
]
}
// Traverse a data structure
// When you traverse an object:
// 1) Get the fields as strings
// 2) Test whether you have a field Flag in your fields
// 3) If you do then rename Flag to PrimaryFlag and add
// the Code field to the current object
// Traversal stops at this point
// 4) If you don't then just traverse object and recursivelly
// traverse the values
// When you traverse an array:
// 1) Iterate over the array
// 2) Traverse every single element in the array
// For all other types default will execute.
%function traverse(ds) ds match {
:object -> using (
fs = $ pluck $$ as :string
) (
(
$ - "Flag" ++ {PrimaryFlag: $.Flag,Code: [{code: null}]}
when (fs contains "Flag")
otherwise ($ mapObject {($$): traverse($)})
)
),
:array -> $ map traverse($),
default -> $
}
---
traverse(data)
我不得不做一些假设,例如,字段Flag
在您的数据结构中仅出现一次。