简体   繁体   中英

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.

Sounds like filterObject could work for you. Documentation

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

Another rendition of the same approach.

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

is this what you are looking for?

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

The other rendition being:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM