Reputation: 126
I need to do dataweave transformation of the key, if it is present and not if the key is not present.
Sample Input
[
{
"Key1": "Value1",
"Key2": {
"Key2.1": "value2.1",
"Key2.2": "Value2.2"
},
"Key3": "Value3",
},
{
"Key1": "Value11",
"Key2": {
"Key2.1": "value22.1"
}
}
]
Sample OutPut
[
{
"KeyA": "Value1",
"KeyB": {
"KeyB.1": "value2.1",
"KeyB.2": "Value2.2"
},
"KeyC": "Value3"
},
{
"KeyA": "Value11",
"KeyB": {
"KeyB.1": "value22.1"
}
}
]
Not Expected
[
{
"KeyA": "Value1",
"KeyB": {
"KeyB.1": "value2.1",
"KeyB.2": "Value2.2"
},
"KeyC": "Value3"
},
{
"KeyA": "Value11",
"KeyB": {
"KeyB.1": "value22.1"
"KeyB.2": null
},
"KeyC": null
}
]
Question1: Is it really a JSON format?
Question2: How to do such transformation in DW 2.0?
Thanks in advance :)
Upvotes: 0
Views: 972
Reputation: 25872
The input is not a valid JSON document because there is an extra comma after Key3, though it is not clear if that is what you are asking or why.
After removing the comma the input is a JSON array of two JSON objects. You can use map() to transform each element and then use mapObject() to transform the keys in each object. mapObject() will not create new keys, only transform the existing ones, so there is no risk of creating new ones. As an example I use a transformKey() to encapsulate the desired transformation of the key. I'm using the built-in lower() function, but you could use whatever logic you want to transform the key.
%dw 2.0
output application/json
fun transformKey(k)= lower(k)
---
payload map (
$ mapObject ((value, key, index) -> (transformKey(key)): value )
)
Upvotes: 1
Reputation: 5059
There are two ways to do this kind of things,
{
(a: payload.a) if(payload.a?)
}
output application/json skipNullOn="everywhere"
---
{
a: payload.a
}
Upvotes: 3