Reputation: 526
I have a Json Input like below, where if doa
is null or "" it needs to replace with the value test
if it contains Value then no change required. I have achieved in dwl 2 version using update
. Using mabObject in dataweave 1.0 version, but it is not working out. Looking for your expertise. Thanks
Input:
{
"sets": {
"exd": {
"cse": {
"doa": null
}
}
}
}
Achieved in dwl 2 :
%dw 2.0
output application/json skipNullOn="everywhere"
import * from dw::util::Values
---
if
(!isEmpty (payload.sets.exd.cse.doa )) payload
else
payload update
{
case .sets.exd.cse.doa! -> "test"
}
Response
{
"sets": {
"exd": {
"cse": {
"doa": "test"
}
}
}
}
Looking for Mule 3 dataweave 1.0 version of it??
Upvotes: 1
Views: 1962
Reputation: 119
As per my comment to @aled's solution, here is an update that will limit the change to the specific key even if there are multiple key-value pairs at the target level:
%dw 1.0
%output application/json
%function updateKey(o,keys,value)
o match {
:object -> o mapObject ($$):
updateKey($, keys[1 to -1], value )
when ($$ ~= keys[0] and ((sizeOf keys) >1))
otherwise ($ when (((sizeOf keys) >1) or '$$' != keys[0])
otherwise value
),
default -> $
}
---
updateKey(payload, ["sets", "exd", "cse", "doa"], "test") when (payload.sets.exd.cse.doa is :null or payload.sets.exd.cse.doa == "") otherwise payload
Upvotes: 0
Reputation: 25872
This is a lesser backport of the update operator in DataWeave 2.0 to DataWeave 1.0 as a function. The keys parameter is the sequence of keys as an array as strings. I added a check for key null or empty as it can be done in DataWeave 1.0.
%dw 1.0
%output application/json
%function updateKey(o,keys,value)
o match {
:object -> o mapObject ($$):
updateKey($, keys[1 to -1], value )
when ($$ ~= keys[0] and ((sizeOf keys) >1))
otherwise ($
when ((sizeOf keys) >1) otherwise value
),
default -> $
}
---
updateKey(payload, ["sets", "exd", "cse", "doa"], "test") when (payload.sets.exd.cse.doa is :null or payload.sets.exd.cse.doa == "") otherwise payload
Upvotes: 1
Reputation: 1910
If / else statements work considerably differently in dataweave 1.0, update
doesn't exist, and I don't know if isEmpty
exists as part of core - don't think so. If you know ahead of time the structure of the object, you can simply build a new object like this:
%dw 1.0
%input payload application/json
%output application/json
---
payload when (payload.sets.exd.cse.doa != '' and payload.sets.exd.cse.doa != null)
otherwise {
sets: {
exd: {
cse: {
data: "test"
}
}
}
}
Upvotes: 0