JsonPath:按数组中的值筛选

2022-09-03 12:40:55

我正在尝试使用Jsonpath按值筛选Json中的数组。我想在下面的JSON中获取该国的long_name。为了做到这一点,我按类型[0]==“国家”过滤adress_components,但它似乎不起作用。

我尝试过的 JsonPath :

$.results[0].address_components[?(@['types'][0]=="country")].long_name

我想要的结果是:“加拿大”。

JSON :

{
       "results" : [
          {
             "address_components" : [
                {
                   "long_name" : "5510-5520",
                   "short_name" : "5510-5520",
                   "types" : [ "street_number" ]
                },
                {
                   "long_name" : "Yonge Street",
                   "short_name" : "Yonge St",
                   "types" : [ "route" ]
                },
                {
                   "long_name" : "Willowdale",
                   "short_name" : "Willowdale",
                   "types" : [ "neighborhood", "political" ]
                },
                {
                   "long_name" : "North York",
                   "short_name" : "North York",
                   "types" : [ "political", "sublocality", "sublocality_level_1" ]
                },
                {
                   "long_name" : "Toronto",
                   "short_name" : "Toronto",
                   "types" : [ "locality", "political" ]
                },
                {
                   "long_name" : "Toronto Division",
                   "short_name" : "Toronto Division",
                   "types" : [ "administrative_area_level_2", "political" ]
                },
                {
                   "long_name" : "Ontario",
                   "short_name" : "ON",
                   "types" : [ "administrative_area_level_1", "political" ]
                },
                {
                   "long_name" : "Canada",
                   "short_name" : "CA",
                   "types" : [ "country", "political" ]
                },
                {
                   "long_name" : "M2N 5S3",
                   "short_name" : "M2N 5S3",
                   "types" : [ "postal_code" ]
                }
             ]
            }
       ],
       "status" : "OK"
}

感谢您的帮助。


答案 1

以下 JSONPath 将起作用:

$..address_components[?(@.types[0] == 'country')].long_name

分解:

  • $..address_components:聚焦于阵列address_components
  • [?(@.types[0] == 'country')]:查找具有名为“type”的类型属性的子文档,该属性包含一个数组,其中第一个值为“国家/地区”address_components
  • .long_name:返回此子文档的属性。long_name

使用 Jayway JsonPath Evaluator 和 Java 进行验证:

JSONArray country = JsonPath.parse(json)
    .read("$..address_components[?(@.types[0] == 'country')].long_name");

// prints Canada
System.out.println(country.get(0));

答案 2

如果国家不是类型数组中的第一个,则glytching提供的工作解决方案将不再存在。

您应该使用:

$..address_components[?(@.types.indexOf('country') != -1)]

它将按包含国家/地区的数组进行过滤,而不是以国家/地区开头的数组