I am trying to filter a particular value coming from a JSON array. My sample array is given below:
"source":[
{
"value": {
"Type": [
{
"val": "Primary",
"code": "PRI"
}
],
"Value": [
{
"val": "PHAR",
"Code": "Pharmacy"
}
]
}
},
{
"value": {
"Type": [
{
"val": "Secondary",
"code": "SEC"
}
],
"Value": [
{
"val": "HOSP",
"Code": "Hospital"
}
]
}
}
]
In the above, I need to read the first occurrence of source.value.Value.val where source.value.Type.code=="SEC" My array can have multiple codes like "PRI", "SEC" etc and I need to get the data for code = "SEC" only (first occurance)
You can use the filter function to filter your array.
%dw 1.0
%output application/json
---
{
output: payload.source filter ($.value.Type[0].code == "SEC")
}
the above code will produce the following output:
{
"output": [
{
"value": {
"Type": [
{
"val": "Secondary",
"code": "SEC"
}
],
"Value": [
{
"val": "HOSP",
"Code": "Hospital"
}
]
}
}
]
}
Amendment : Here is the new piece of code which will give you only the value you are looking for and not the whole Array
%dw 1.0
%output application/json skipNullOn="everywhere"
---
{
(payload.source default [] map (source, indexOfSource) -> {
output: source.value.Value[0].val when source.value.Type[0].code == "SEC" otherwise null
})
}
The output of the above piece of code is:
{
"output": "HOSP"
}
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.