Ravindar, Integrations with Mulesoft & BizTalk

Just another Integration blog

Search for a key with a specific value and pick that corresponding record’s values

We had a special requirement of searching json values (instead of keys) and pick the corresponding record other keys value

for example in the following example, products is an array and the json keys names inside the products.sections for each array item are dynamic. Means the keys can come like sec_Name1 or sec_Name3 or any other key name dynamically.

{
  "products": [
    {
      "code": "1",
      "name_1": "2",
      "area_A": "A1",
      "sections": null
    },
    {
      "code": "6",
      "name_2": "B2",
      "area_B": "B2",
      "sections": {
        "sec_Name3": "test3",
        "sec_Name2": "test4",
        "sec_name_n": "test..n"
      }
    },
    {
      "code": "9",
      "name_2": "B2",
      "area_B": "A1",
      "area_C": "A1",
      "sections": {
        "sec_Name3": "test2",
        "sec_Name2": "test4",
        "sec_name_n": "test..n"
      }
    }
  ]
}

Now the requirement was to search if any of keys inside the “sections” has a specific value say “test2” for example, then pick the Product.Code.

So two things
1. we need to search all the keys under “sections”
2. And pick “code” value which is one level up

I’ve used the following 2 approached to pick the value.

you can either use a dataweave expression like below

#[dw('(payload.products map $ filter (($.sections != null) and ($.sections contains "test2"))).code[0]')]

or you can use dataweave trasnformation like below

%dw 1.0
%output application/java
---
{
   Code: (payload.products map $ filter (($.sections != null) and ($.sections contains "test2"))).code[0]
}

probably there are many more ways to achieve this, but these ones worked for me

September 19, 2019 Posted by | Mule 3, Mulesoft | | Leave a comment