2017-07-29 164 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

只需將退出添加到最後一次打印。我編輯過。 –