How to apply filter on nested json array using map function

Applying filter condition to JSON nested array using map function in Dataweave 2.0




Let us see how to apply a filter on a nested JSON array using the map function. We might need to use the map function to filter the parent array & then the second map function to filter the nested array.

Also see: What is the output of map() function in Dataweave 2.0


Below is a sample payload that consists of employee records with different roles. Each record again consists of the nested array with the skills of each employee. Using this payload let us observe different use cases & filter the JSON array list.

Input payload:
{
"users": [
{
"userId": 1,
"firstName": "Uday",
"lastName": "Kiran",
"role": "Developer",
"phoneNumber": "930293029",
"emailAddress": "hello@designgrows.com",
"skillsList": [
{
"skillID": 1,
"skillName": "MuleSoft"
},
{
"skillID": 2,
"skillName": "Java"
}
]
},
{
"userId": 2,
"firstName": "Jake",
"lastName": "Anderson",
"role": "Developer",
"phoneNumber": "7567567567",
"emailAddress": "jake@google.com",
"skillsList": [
{
"skillID": 5,
"skillName": "Salesforce"
},
{
"skillID": 1,
"skillName": "MuleSoft"
}
]
},
{
"userId": 3,
"firstName": "Jayanth",
"lastName": "Arnab",
"phoneNumber": "75675675675",
"role": "Architect",
"emailAddress": "arnab@googlemail.com",
"skillsList": [
{
"skillID": 5,
"skillName": "Salesforce"
},
{
"skillID": 6,
"skillName": "Kubernetes"
},
{
"skillID": 7,
"skillName": "Python"
}
]
}
]
}

Scenario 1: Retrieve all the skills (nested array) when role is "Architect"

Output:



Dataweave code:
%dw 2.0
output application/json
---
payload.users filter ($.role =="Architect") map {
"skillsList": $.skillsList map {
"skillId":$.skillID,
"skillName":$.skillName
}
}

Scenario 2: Retrieve only specific skills(nested array) when role is "Architect". In this scenario we are using the map function one more time to filter the nested array.

Output:


Dataweave code:
%dw 2.0
output application/json
---
payload.users filter ($.role =="Architect") map {
"skillsList": $.skillsList filter ($.skillID > 6) map {
"skillId":$.skillID,
"skillName":$.skillName
}
}

Also see: Simple use of filter, contains in Dataweave 2.0 on JSON message


Scenario 3: Retrieve the "skillName" with "skillID" as 6
Output:



Dataweave code:
%dw 2.0
output application/json
var skills=payload.users filter ($.role =="Architect") map { "skillsList": $.skillsList filter ($.skillID == 6) map {
"skillName":$.skillName
}
}
---
flatten(skills.skillsList)

Post a Comment

0 Comments