加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Groovy JSON / GPath查询

发布时间:2020-12-14 16:30:07 所属栏目:大数据 来源:网络整理
导读:鉴于以下 JSON,我想提取postal_code(long_name或short_name).我已经使用JsonSlurper将其摄取到变量中并使用find / contains / etc尝试了各种查询.抓住在“类型”中有“postal_code”但仍无法解决的节点.任何帮助是极大的赞赏. { "results" : [ { "address_co
鉴于以下 JSON,我想提取postal_code(long_name或short_name).我已经使用JsonSlurper将其摄取到变量中并使用find / contains / etc尝试了各种查询.抓住在“类型”中有“postal_code”但仍无法解决的节点.任何帮助是极大的赞赏.

{
   "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",{
               "long_name" : "Virginia","short_name" : "VA","types" : [ "administrative_area_level_1",{
               "long_name" : "United States","short_name" : "US","types" : [ "country",{
               "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"
}

解决方法

以下应该找到具有postal_code类型的节点.如果结果或address_components有多个列表项,则必须通过用一些迭代替换索引访问来相应地进行调整,但希望这会有所帮助.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读