'Map an additional key-value in a specific index of a json array using Dataweave 2.0
I have an input payload (json array) that needs to be enriched with a key-value in a specific index. My requirement was to put the additional key-value (the same for all objects) at index 1, so i've managed to do like this:
Input payload:
[
{
"key1": "value1",
"key3": "value3",
"key4": "value4",
"key5": "value5"
},
{
"key1": "value1",
"key3": "value3",
"key4": "value4",
"key5": "value5"
},
{
"key1": "value1",
"key3": "value3",
"key4": "value4",
"key5": "value5"
}
]
Script:
%dw 2.0
output application/json
---
payload map (
($)[&0] ++ {"key2": "value2"} ++ ($ - "key1")
)
Output:
[
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5"
}
]
My question is: how to achieve this dynamically?
Thanks, Marco
Solution 1:[1]
- Preserving the keys of payload first so that we can interate from 2nd element to n-1
- k[1 to -1] since you want to insert at 1st index position ignoring the 1st key element
DW
%dw 2.0
output application/json
var k=keysOf(payload[0])
---
payload map(item,index)-> (
[(item[&0])] ++ [{"key2": "value2"}] ++ (k[1 to -1] map ($): (item[$]))
) reduce($$++$)
Alternatitevely You can use MinusMinus to remove an element
%dw 2.0
output application/json
---
payload map (
($)[&0] ++ {"key2": "value2"} ++ ($ -- (($)[&0]))
)
Output
[
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5"
}
]
Solution 2:[2]
First I would remove the key in case it is already present, then add the new key pair dynamically. You could omit the removal if you are sure the key doesn't previously exists in the input elements.
%dw 2.0
output application/json
var key="key2"
var value="value2"
---
payload map (
$ - key ++ {(key): value}
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | aled |
