2016-02-24 47 views
-3

如何在Python中使用文件json中lat/lng的Reverse Geocoding。之後,打印文件json的位置名稱。如何從python中獲取值json的位置?

import json 

Json_data=[{"lat":"3.160","lng":"101.710"}, 
      {"lat":"2.350","lng":"102.030"}, 
      {"lat":"6.120","lng":"102.130"}] 

#Json_data=[{"lat":3.160,"lng":101.710}, 
#   {"lat":2.350,"lng":102.030}, 
#   {"lat":6.120,"lng":102.130}] 

def revrseGeocode(latlng): 
    result={} 
    url ='https://maps.googleapis.com/maps/api/geocode/json?latlng={0} &key={1}' 
    apikey='AIzaSyC6gSdW2pWz9QgaBY2ZlZcYRTKva9-x74w' 
    request= url.format(latlng,apikey) 
    data= json.loads(request) 
    if len(data['results'])>0: 
     result=data['results'][0] 
     return result 

for i,row in Json_data: 
    Json_data[i]= revrseGeocode(Json_data[1][i]+','+Json_data[1][i]) 

for i,row in Json_data: 
    if 'address_components' in row['geocode_data']: 
     for component in row['geocode_data']['address_components']: 
      if 'country' in component['types']: 
       Json_data['country'][i]= component['long_name'] 
     for component in row['geocode_data']['address_components']: 
      if 'locality' in component['types']: 
       Json_data['city'][i]=component['long_name'] 
       break 
      elif 'postal_town' in component['types']: 
       Json_data['city'][i] = component['long_name'] 
       break 
      elif 'administrative_area_level_2' in component['types']: 
       Json_data['city'][i]=component['long_name'] 
       break 
      elif 'administrative_area_level_1' in component['types']: 
       Json_data['city'][i]= component['long_name'] 
       break 

#ERROR:所有Json_data的

File "/home/magic/Desktop/python/test1.py", line 22, in Json_data[i]= revrseGeocode(Json_data[1][i]+','+Json_data[1][i])

File "/home/magic/Desktop/python/test1.py", line 16, in revrseGeocode data= json.loads(request)

File "/usr/lib/python2.7/json/init.py", line 338, in loads return _default_decoder.decode(s)

File "/usr/lib/python2.7/json/decoder.py", line 366, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end())

File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded

+0

「反向地理編碼」是什麼意思?請提供詳情。至少,說明預期的產出。 – jorgeh

+0

當你研究這個時,你發現了什麼? –

+0

我的意思是得到國家。 – kenzi

回答

0

首先是一個列表。您可以通過Jason_data [index]訪問它,其中索引可以是0到len(Jason_data)之間的任何數字。

您正試圖以字典的形式訪問它。因此錯誤。