json - Groovy JSON/GPath 查询

标签 json groovy gpath

鉴于以下 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", "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"
}

最佳答案

下面应该找到具有 postal_code 类型的节点。如果resultsaddress_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

关于json - Groovy JSON/GPath 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12378726/

相关文章:

validation - belongsTo 在每个场景中的表现都不同

java - 使用 REST 确保的 XmlPath 查找所有 XML 节点

android - 如何在 android 中使用 groovy 制作 integrationTest 源集?

groovy - 使用 XmlSlurper 和 findAll 的嵌套 GPath 表达式

xml - 使用 Groovy (gpath) 获取 XML 属性的值

javascript - 阻止 JSON.parse 删除反斜杠和后面的字母?

javascript - 使用 JavaScript 解析 JSON 文件

java - 并行解析n个JSON对象并形成聚合json的优化方法

ios - "Ambiguous use of subscript"新 Swift 更新后出错

grails - 从我不想持久化的getter方法返回默认实例