JsonPath : filter by value in array
The working solution offered by glytching won't anymore if country is not the first one of the types array.
You should rather use:
$..address_components[?(@.types.indexOf('country') != -1)]
It will filter by array contains country, rather than array starts with country
The following JSONPath will work:
$..address_components[?(@.types[0] == 'country')].long_name
Breaking it down:
$..address_components
: focus on theaddress_components
array[?(@.types[0] == 'country')]
: find theaddress_components
sub document having a type attribute named "type" containing an array of which the first value is "country".long_name
: return thelong_name
attribute of this sub document.
Verified using the Jayway JsonPath Evaluator and in Java:
JSONArray country = JsonPath.parse(json)
.read("$..address_components[?(@.types[0] == 'country')].long_name");
// prints Canada
System.out.println(country.get(0));