簡體   English   中英

JsonPath:按數組中的值過濾

[英]JsonPath : filter by value in array

我正在嘗試使用 Jsonpath 按值過濾我的 Json 中的數組。 我想在下面的 JSON 中獲取國家/地區的 long_name。 為了做到這一點,我按類型 [0] == "country" 過濾了 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"
}

謝謝您的幫助。

以下 JSONPath 將起作用:

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

分解它:

  • $..address_components : 關注address_components數組
  • [?(@.types[0] == 'country')] :找到具有名為“type”的類型屬性的address_components子文檔,其中包含第一個值為“country”的數組
  • .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));

如果country不是類型數組中的第一個,則 glytching 提供的工作解決方案將不再適用。

你應該使用:

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

它將按包含國家/地區數組過濾,而不是以國家/地區開頭的數組

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM