我的json有效载荷如下。
Attributes:{
Contact:{
Address:{
PersonName:"John",
Line1:"sdsds",
Line2:"sdsdsd",
SubAddress:{
PersonName:"John",
Line1:"ggghg",
Line2:"xzxzxzx"
}
},
Phone:{
Home:"2323232323",
Office:"4545454545"
}
},
Id:"2343434",
order:"3343434"
}
我想把层次结构扁平化到下面输出。
Attributes:{
Contact.Address.PersonName:"John",
Contact.Address.Line1:"sdsds",
Contact.Address.Line2:"sdsdsd",
Contact.Address.SubAddress.PersonName:"John",
Contact.Address.SubAddress.Line1:"ggghg",
Contact.Address.SubAddress.Line2:"xzxzxzx",
Contact.Phone.Home:"2323232323",
Contact.Phone.Office:"4545454545",
Id:"2343434",
order:"3343434"
}
Attributes元素可以有任何数量的复杂元素,如 "地址 "和 "联系人"。我们在编码时不会知道复杂元素的键值。DWL应能产生单级输出。想要在Mule 3中使用dw1来解决这个扁平化的通用方案。请你帮忙
下面的脚本递归地查看有效载荷,并构建单个键值对对象。
%dw 1.0
%output application/json
%var payload = {"Attributes":{"Contact":{"Address":{"SubAddress":[{"PersonName1":"John","Line1":"ggghg","Line2":"xzxzxzx"},{"PersonName":"Jar","Line1":"ggghg","Line2":"xzxzxzx"}]},"Phone":{"Home":"2323232323","Office":"4545454545"}},"Id":"2343434","order":"3343434"}}
%function constructKeys(oldKeys, newKey) oldKeys ++ '.' ++ newKey
%function writeData(json ,output, keys) json match {
case is :null -> null,
case is :array -> {(json map ((item, index) -> writeData(item, output, keys ++ index)))},
case is :object -> {((json pluck $$) map writeData(json[$],output,constructKeys(keys,$)))},
default -> output ++ {(keys[1 to -1]): json }
}
---
Attributes: writeData(payload.Attributes,{}, '')