gpt4 book ai didi

java - JsonPath : filter by value in array

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:48:02 26 4
gpt4 key购买 nike

我正在尝试使用 Jsonpath 按值过滤我的 Json 中的数组。我想在下面的 JSON 中获取国家/地区的 long_name。为此,我按 types[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')]:找到 address_components 子文档,其类型属性名为“type”,包含一个数组其中第一个值为“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));

关于java - JsonPath : filter by value in array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47576119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com