首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Groovy JSON/GPath查询

Groovy JSON/GPath查询
EN

Stack Overflow用户
提问于 2012-09-12 06:15:08
回答 1查看 16K关注 0票数 7

给定以下JSON,我想提取postal_code ( long_name或short_name)。我已经使用JsonSlurper将其摄取到一个变量中,并尝试了使用find/contains/等进行各种查询,以获取“类型”中包含"postal_code“的节点,但仍无法找出它。任何帮助都是非常感谢的。

代码语言:javascript
复制
{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Jefferson Ave",
               "short_name" : "Jefferson Ave",
               "types" : [ "route" ]
            },
            {
               "long_name" : "North Newport News",
               "short_name" : "North Newport News",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "Newport News",
               "short_name" : "Newport News",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Virginia",
               "short_name" : "VA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "23608",
               "short_name" : "23608",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "Jefferson Ave & Denbigh Blvd, Newport News, VA 23608, USA",
         "geometry" : {
            "location" : {
               "lat" : 37.13852930,
               "lng" : -76.52013079999999
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 37.13987828029151,
                  "lng" : -76.51878181970848
               },
               "southwest" : {
                  "lat" : 37.13718031970851,
                  "lng" : -76.52147978029149
               }
            }
         },
         "types" : [ "intersection" ]
      }
   ],
   "status" : "OK"
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-12 07:15:16

下面的代码应该会找到postal_code类型的节点。如果resultsaddress_components有多个列表项,您必须相应地进行调整,将索引访问替换为一些迭代,但希望这会有所帮助。

代码语言:javascript
复制
import groovy.json.*

def text = '''
{
   "results" : [
<omitted rest to save space>
....
}
'''

def json = new JsonSlurper().parseText(text)

def theNode = json.results[0]
                  .address_components
                  .find { it.types[0] == 'postal_code' }

assert '23608' == theNode.long_name
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12378726

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档