Thinker-101
Thinker-101

Reputation: 651

Extracting a subset of JSON key-value pairs as an Object from a Parent JSON Object in dataweave 2.0 Mule 4

I have a dataweave challenge which I couldn't figure out without making it complicated.

Input JSON payload

{
   "Name"     : "Mr.wolf",
   "Age"      : 26,
   "Region"   : "USA",
   "SubRegion": "Pacific"
}

Output needed

{
   "Name"     : "Mr.wolf",
   "Age"      : 26
}

Here is a catch. I am not allowed to use the above shown output format structure in the transform message, or either remove the keys using "-" operation.

So basically, we shouldn't use the below dwl.

%dw 2.0
output application/json
---
(payload - "Region" - "SubRegion")

or

%dw 2.0
output application/json
---
{
   "Name"     : payload.Name,
   "Age"      : payload.Age
}

How can we achieve the required output by using Lambdas, Reduce, mapObject, functions or any other operation of choice, other than the restricted methods/usage shown above.

Any solution provided is much appreciated.

Upvotes: 1

Views: 1742

Answers (4)

Salim Khan
Salim Khan

Reputation: 4303

The other rendition being:

%dw 2.0
output application/json
---
payload mapObject {
    (($$) : $) if (($$$) < 2)
}

Upvotes: 0

Salim Khan
Salim Khan

Reputation: 4303

is this what you are looking for?

%dw 2.0
output application/json
---
payload filterObject ((value, key,index) -> (index <2 ))

Upvotes: 1

Salim Khan
Salim Khan

Reputation: 4303

Another rendition of the same approach.

%dw 2.0
output application/json
---
payload mapObject {
    (($$) : $) if (($$) ~= "Name" or ($$) ~= "Age")
}

Upvotes: 1

short stack stevens
short stack stevens

Reputation: 692

Sounds like filterObject could work for you. Documentation

payload filterObject ((value, key) -> (key ~= "Name" or key ~= "Age"))

Upvotes: 1

Related Questions