How to get location from get value json in python?

How to use Reverse Geocoding from lat/lng in file json by Python. After that print file json location name.

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:

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


First of all your Json_data is a list. You can access it by Jason_data[index],where index can be any number between 0 to len(Jason_data).

You are trying to access it as a dictionary. Hence the error.

链接地址: http://www.djcxy.com/p/48680.html

上一篇: 不能解析json文件,说没有JSON对象可以被解码

下一篇: 如何从python中获取值json的位置?