I have json payload as below:
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"
}
I want to flatten the hierarchy to below output
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 element can have any number of complex elements like the "Address" and "Contact". We will not know the key value of the complex elements at the point of coding. DWL should be able to produce a single level output. Want generic solution for this flattening using dw1 in Mule 3. Please help.
Below scripts recursively goes over the payload and construct single key-valued pair object
%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,{}, '')