2017-07-29 165 views
0

我使用curl的纬度和经度(bash)的解析谷歌地图API

`curl "https://maps.googleapis.com/maps/api/geocode/json?address=$WHERE&key=$API_KEY"` 

,其结果是

`

{ 
    "results" : [ 
     { 
     "address_components" : [ 
      { 
       "long_name" : "Saket", 
       "short_name" : "Saket", 
       "types" : [ "political", "sublocality", "sublocality_level_1" ] 
      }, 
      { 
       "long_name" : "New Delhi", 
       "short_name" : "New Delhi", 
       "types" : [ "locality", "political" ] 
      }, 
      { 
       "long_name" : "South Delhi", 
       "short_name" : "South Delhi", 
       "types" : [ "administrative_area_level_2", "political" ] 
      }, 
      { 
       "long_name" : "Delhi", 
       "short_name" : "DL", 
       "types" : [ "administrative_area_level_1", "political" ] 
      }, 
      { 
       "long_name" : "India", 
       "short_name" : "IN", 
       "types" : [ "country", "political" ] 
      }, 
      { 
       "long_name" : "110017", 
       "short_name" : "110017", 
       "types" : [ "postal_code" ] 
      } 
     ], 
     "formatted_address" : "Saket, New Delhi, Delhi 110017, India", 
     "geometry" : { 
      "bounds" : { 
       "northeast" : { 
        "lat" : 28.529262, 
        "lng" : 77.2166529 
       }, 
       "southwest" : { 
        "lat" : 28.517834, 
        "lng" : 77.20113789999999 
       } 
      }, 
      "location" : { 
       "lat" : 28.5245787, 
       "lng" : 77.206615 
      }, 
      "location_type" : "APPROXIMATE", 
      "viewport" : { 
       "northeast" : { 
        "lat" : 28.529262, 
        "lng" : 77.2166529 
       }, 
       "southwest" : { 
        "lat" : 28.517834, 
        "lng" : 77.20113789999999 
       } 
      } 
     }, 
     "place_id" : "ChIJ3T8F3fDhDDkRnxNgWBpc2Zc", 
     "types" : [ "political", "sublocality", "sublocality_level_1" ] 
     } 
    ], 
    "status" : "OK" 
}` 

我如何才能获得东北纬度和经度使用bash?你能告诉我应该如何通过jq或其他选择来解析它吗?我需要将值保存在不同的文本文件中。即lat.txt和long.txt。 我打算将纬度和经度作为变量传递,并在另一个API中使用它们来使用经度和纬度获取空气质量。即使是一种替代方案,我也能从中获得更多的经验。

+1

[解析JSON与Unix工具(可能的重复https://stackoverflow.com/questions/1955505/parsing-json-with-unix-tools) – Dekker

回答

0

你可以jq这样的尝试阅读:

curl ... | jq -r '.results[0].geometry.bounds.northeast | "\(.lat) \(.lng)"' 

输出:

28.529262 77.2166529 

或者:

curl ... | jq '.results[0].geometry.bounds.northeast | .lat, .lng' 

输出:

28.529262 
77.2166529 
0

这是相当简单的,我们给出知道有只有两个,我们关心的是(经度和纬度),并给出了JSON格式是固定的,通过AWK所以管道curl命令行:

curl "https://maps.googleapis.com/maps/api/geocode/json?address=$WHERE&key=$API_KEY" | awk '/northeast/ {getline;print;getline;print;exit}' 

搜索东北部,然后进行模式匹配,然后在接下来的记录/行,打印(经度),然后在接下来的记录和打印(纬度)读取

+0

它的工作原理是给我2个纬度和2个经度,我怎么才能得到前2个? –

+0

您是否在运行之前设置了WHERE和API_KEY变量? –

+0

只需将退出添加到最后一次打印。我编辑过。 –