2012-09-11 30 views
6

Với JSON sau, tôi muốn trích xuất mã bưu điện (hoặc long_name hoặc short_name). Tôi đã sử dụng JsonSlurper để nhập nó vào một biến và đã thử các truy vấn khác nhau bằng cách sử dụng find/contains/etc. để lấy nút có "postal_code" trong "loại" của nó nhưng không thể tìm ra. Bất kỳ trợ giúp nào cũng được đánh giá rất cao.Truy vấn JSON/GPath Groovy

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

Trả lời

9

Sau đây sẽ tìm nút có loại bưu điện. Nếu results hoặc address_components từng có nhiều mục danh sách, bạn sẽ phải điều chỉnh cho phù hợp bằng cách thay thế quyền truy cập được lập chỉ mục bằng một số lần lặp lại, nhưng hy vọng điều này sẽ hữu ích.

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 
+3

@GaryWhite +1 Và nếu như John nói, bạn có nhiều kết quả hoặc mã bưu chính, điều này sẽ hoạt động: 'List codes = json.results.address_components * .findAll {'postal_code' in it.types}. flatten(). long_name' –