Groovy JSON/GPath查询

Groovy JSON/GPath查询,json,groovy,gpath,Json,Groovy,Gpath,给定以下JSON,我想提取邮政编码(长名称或短名称)。我曾使用JsonSlurper将其吸收到变量中,并尝试使用find/contains/etc进行各种查询,以获取在其“类型”中包含“邮政编码”但无法识别的节点。非常感谢您的帮助 { "results" : [ { "address_components" : [ { "long_name" : "Jefferson Ave",

给定以下JSON,我想提取邮政编码(长名称或短名称)。我曾使用JsonSlurper将其吸收到变量中,并尝试使用find/contains/etc进行各种查询,以获取在其“类型”中包含“邮政编码”但无法识别的节点。非常感谢您的帮助

{
   "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"
}

以下内容应找到具有邮政编码类型的节点。如果
结果
地址_组件
有多个列表项,则必须通过使用迭代替换索引访问来进行相应调整,但希望这会有所帮助

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
import groovy.json*
定义文本=“”
{
“结果”:[
....
}
'''
def json=new JsonSlurper().parseText(文本)
def theNode=json.results[0]
.address\u组件
.find{it.types[0]=“邮政编码”}
断言'23608'==node.long\u名称

@GaryWhite+1如果正如John所说,您有多个结果或邮政编码,那么这应该是可行的:
List codes=json.results.address\u components*.findAll{it.types}.flatte().long\u name