我试图在Python中开始使用JSON,但似乎我误解了JSON概念中的一些东西。我遵循了google api example,它工作得很好。但是,当我在JSON响应中将代码更改为较低级别时(如下所示,在这里我尝试访问该位置),我将收到以下代码的错误消息:
回溯(最近一次呼叫时间):
文件“geoCode.py”,第11行,in<module>
test=json.dumps(jsonResponse['results']]中s的[s['location'],
indent=3)KeyError:'位置'
如何在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
最佳答案
理解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
对每个迭代的dict通过循环。
s['geometry']
是一个指令。s['geometry']['location']
(最后!)包含
纬度/经度。