I'm trying to filter by value an array in my Json with Jsonpath. I want to get the locationLegalName of the location in the JSON below.
For instance, I have a code CC024 and i need to compare with this json and where the location code is matching i want to extract the locationLegalName. Here in this case it will be Hotel Punta Cana.
Similarly, another example, I have a code CC021 and for that output will be Restaurant Punta Cana.
Can anyone help me with jsonPath?
[
{
"propertyId": 171
"locations": [
{
"locationId": 362,
"locationCode": "CC001",
"locationLegalName": "Hotel Atlantic City",
"locationLongName": "Hotel Atlantic City",
"locationShortName": "Hotel Atlantic City"
}
]
},
{
"propertyId": 174,
"locations": [
{
"locationId": 435,
"locationCode": "CC021",
"locationLegalName": "Restaurant Punta Cana",
"locationLongName": "Restaurant Punta Cana",
"locationShortName": "Restaurant Punta Cana"
},
{
"locationId": 436,
"locationCode": "CC024",
"locationLegalName": "Hotel Punta Cana",
"locationLongName": "Hotel Punta Cana",
"locationShortName": "Hotel Punta Cana"
}
]
}
]
I tried couple of jsonPath expressions but unable to write anything.
What I would do is gather all of the locations first using a recursive descent operator ..locations
. Then it's pretty simple to filter through those to isolate the one you want.
$..locations[?@.locationCode=='CC021'].locationLegalName
Broken out:
$..locations (1)
[?@.locationCode=='CC021'] (2)
.locationLegalName (3)
locationCode == 'CC021'
. The result here is a collection of objects.locationLegalName
of any that are returned. The result here is a collection of strings.This can be tested on https://json-everything.net/json-path (my playground).