简体   繁体   中英

Filter an Array of Json From Mule Dataweave

My Request Json Looks like below. I want to retrieve all the productNumber which has got the roles as test.

{
   "productRelation": [
      {
         "productNumber": 12345,
         "roles": [
            {
               "role": {
                  "code": "test",
                  "description": "test"
               }
            }
         ]
      },
      {
         "productNumber": 789,
         "roles": [
            {
               "role": {
                  "code": "dev",
                  "description": "dev"
               }
            }
         ]
      },
      {
         "productNumber": 111,
         "roles": [
            {
               "role": {
                  "code": "prod",
                  "description": "prod"
               }
            }
         ]
      }
   ]
}

I tried using dataweave filter to filter it out. I use mule 4 and dataweave 2.0

Using filter:

%dw 2.0
output application/json
---
payload.productRelation 
    filter ((item, index) -> item.roles..code contains "test") 
    map ((item, index) -> item.productNumber)

Try this:

%dw 2.0
output application/json
---
payload.productRelation reduce (e, acc=[]) -> (
    do {
        // Get the roles for the productNumber]
        var roles = e.roles..*code
        ---
        // if the roles contain test add the productNumber to the result
        if (roles contains "test") (acc + e.productNumber) else acc
    }
)

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