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 the address_components array
  • [?(@.types[0] == 'country')]: find the address_components sub document having a type attribute named "type" containing an array of which the first value is "country"
  • .long_name: return the long_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));