Hello friends,
In this article I will show you how we can filter results from complex Arrays. In this use-case we will use select and descendent operators from Mulesoft dataweave.
In this use-case we will try to find out the Book details which is at-least rented once from Library. We will see some variations to dataweave expressions in below section.
Input Payload:
[ { "bookId": "20200114", "bookType": "Fiction", "title": { "en": "Candide" }, "message": { "en": "" }, "bookDetails": [ { "label": { "en": "Candide" }, "Library": { "city": "Pune", "rented": { "count": "1" } } } ] }, { "bookId": "20200115", "bookType": "Fiction", "title": { "en": "The Alchemist" }, "message": { "en": "" }, "bookDetails": [ { "label": { "en": "The Alchemist" }, "Library": { "city": "Kolkata", "rented": { "count": "0" } } } ] } ]
%dw 2.0 output application/json --- payload[?($.bookDetails.Library.rented.count[0] >= "1")] default []
[ { "bookId": "20200114", "bookType": "Fiction", "title": { "en": "Candide" }, "message": { "en": "" }, "bookDetails": [ { "label": { "en": "Candide" }, "Library": { "city": "Pune", "rented": { "count": "1" } } } ] } ]
Now let us understand the dataweave script in some details:
DW-Script |
We can add multiple conditions inside red brackets based on our requirement.
%dw 2.0 output application/json --- payload[?(($.bookDetails.Library.rented.count[0] >= "1") and ($.bookDetails.Library.city[0] == "Pune"))] default []
%dw 2.0 output application/json --- payload[?(($.bookDetails.Library.rented.count[0] >= "1") and ($.bookDetails.Library.city contains "Pune"))] default []
%dw 2.0 output application/json --- payload[?(($..count[0] >= "1") and ($..city[0] == "Pune"))] default []
%dw 2.0 output application/json --- payload[?(($..count[0] >= "1") and ($..city contains "Pune"))] default []
Some of common useful dataweave use-cases that you can check from our other articles:
- a-complete-dataweave2-selectors-hack
- how-to-lookup-csv-table-using-dw2
- pattern-matching-in-dw-using-match-case
- splitby-and-joinby-function-dataweave
- array-comparison-use-case-dw2
- dataweave-useful-string-functions-part1
- optimize-json-data-using-dataweave
- how-to-write-attributes-from-xml-to-json-dw2
- use-secure-properties-in-dw2
Also, there are a lot selectors available in Mulesoft docs which you can explore from here.
relevant web page