用Python解析JSON文件 -> Google地图API
我正在尝试在Python中使用JSON,但似乎对JSON的概念有些误解。我跟着谷歌API的例子,这个例子运行得很好。但是当我把代码改成去访问JSON响应中的更低层级(如下所示,我试图获取位置)时,出现了以下错误信息:
追踪记录(最近的调用在最前面):
文件 "geoCode.py",第11行,在
<module>
test = json.dumps([s['location'] for s in jsonResponse['results']], indent=3) KeyError: 'location'
我该如何在Python中访问JSON文件中的更低层级信息?我是否需要先去更高层级再搜索结果字符串?这对我来说似乎很奇怪?
这是我尝试运行的代码:
import urllib, json
URL2 = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false"
googleResponse = urllib.urlopen(URL2);
jsonResponse = json.loads(googleResponse.read())
test = json.dumps([s['location'] for s in jsonResponse['results']], indent=3)
print test
2 个回答
0
首先让人困惑的是,使用 import json 时,loads 这个功能是不可用的。其实你需要这样导入:
import simplejson as json,所以:
import urllib
import simplejson as json
import pprint
URL2 = "http://pbx/a/kiosks"
googleResponse = urllib.urlopen(URL2)
jsonResponse = json.loads(googleResponse.read())
pprint.pprint(jsonResponse)
18
理解 jsonResponse
的格式,最好的办法就是把它打印出来:
import urllib, json
import pprint
URL2 = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false"
googleResponse = urllib.urlopen(URL2)
jsonResponse = json.loads(googleResponse.read())
pprint.pprint(jsonResponse)
# {u'results': [{u'address_components': [{u'long_name': u'1600',
# u'short_name': u'1600',
# u'types': [u'street_number']},
# {u'long_name': u'Amphitheatre Pkwy',
# u'short_name': u'Amphitheatre Pkwy',
# u'types': [u'route']},
# {u'long_name': u'Mountain View',
# u'short_name': u'Mountain View',
# u'types': [u'locality',
# u'political']},
# {u'long_name': u'San Jose',
# u'short_name': u'San Jose',
# u'types': [u'administrative_area_level_3',
# u'political']},
# {u'long_name': u'Santa Clara',
# u'short_name': u'Santa Clara',
# u'types': [u'administrative_area_level_2',
# u'political']},
# {u'long_name': u'California',
# u'short_name': u'CA',
# u'types': [u'administrative_area_level_1',
# u'political']},
# {u'long_name': u'United States',
# u'short_name': u'US',
# u'types': [u'country',
# u'political']},
# {u'long_name': u'94043',
# u'short_name': u'94043',
# u'types': [u'postal_code']}],
# u'formatted_address': u'1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA',
# u'geometry': {u'location': {u'lat': 37.4216227,
# u'lng': -122.0840263},
# u'location_type': u'ROOFTOP',
# u'viewport': {u'northeast': {u'lat': 37.424770299999999,
# u'lng': -122.0808787},
# u'southwest': {u'lat': 37.418475100000002,
# u'lng': -122.0871739}}},
# u'types': [u'street_address']}],
# u'status': u'OK'}
test = json.dumps([s['geometry']['location'] for s in jsonResponse['results']], indent=3)
print(test)
# [
# {
# "lat": 37.4216227,
# "lng": -122.0840263
# }
# ]
jsonResponse
是一个字典。jsonResponse['results']
是一个字典的列表。- 循环
for s in jsonResponse['results']
会在每次循环中把s
赋值为一个字典。 s['geometry']
也是一个字典。s['geometry']['location']
(终于!)包含了经纬度的字典。