Reputation: 151
I am using dataweave diff function to compare two json objects. Diff is functioning correctly and returning the items that have changed, but it isn't returning anything but the differences. It is returning the path of the item that has changed, but I am not finding a good way to navigate to a string based path. I am only showing one group in the example but there could be many groups by different unique names.
{
"email": "[email protected]",
"frequency": 1,
"group1": [],
"group2": [],
etc...
)
So here is an example of what I am trying to describe:
Payload 1
{
"email": "[email protected]",
"frequency": 1,
"group1": [
{
"name": "item1",
"enabled": true
},
{
"name": "item2",
"enabled": true
},
{
"name": "item3",
"enabled": true
}
]
}
Payload 2:
{
"email": "[email protected]",
"frequency": 1,
"group1": [
{
"name": "item1",
"enabled": true
},
{
"name": "item2",
"enabled": true
},
{
"name": "item3",
"enabled": false
}
]
}
In this case diff between payload 1 and payload 2 would return
{
"matches": false,
"diffs": [
{
"expected": "true",
"actual": "false",
"path": "(root).group1[2].enabled"
}
]
}
I need to reach back into the original payload and navigate to (root).order[2] to get the name key/value pair. What is the best way to do this?
So at the end of the day I need the payload to be:
[
{
name: "item3",
enabled: false,
level: 1
}
]
I appreciate any assistance you can offer. I am also doing a map of the payload level so I know which piece of data to update when I traverse the results. So in this case the level would be 1 based on the fact that is an array off the main object.
This is my current dataweave I just need the first element to be dynamic based on the path that the diff returns
%dw 2.0
output application/json
---
payload.diffs map (item, index) -> {
name: initialPayload.group1[2].name, <-needs to be dynamic based on path
value: (item.actual) replace "\"" with "",
level: sizeOf(item.path splitBy ".")-1
}
Upvotes: 1
Views: 128
Reputation: 151
I was able to resolve the issue with this weave.
%dw 2.0
fun GetValue(group: String, level: Number, itemkey: String) =
GetKeyValue((((group) splitBy /\./ reduce (e, acc = vars.initialPayload) -> acc[e])[level]), itemkey)
fun GetKeyValue(obj: Object, itemKey: String) =
(entriesOf(obj) filter (item) -> item.key as String == itemKey).value[0]
output application/json skipNullOn="everywhere"
---
{
changes: payload.diffs map (item, index) -> {
name:
if (sizeOf(item.path splitBy ".") - 1 == 1)
((item.path splitBy ".")[1])
else
GetValue((((item.path splitBy ".")[1]) splitBy "[")[0], (((item.path splitBy ".")[1]) splitBy "[")[1] replace "]" with "", "name"),
value: item.actual replace "\"" with "",
level: (sizeOf(item.path splitBy ".") - 1),
}
}
Upvotes: 1