在Python中解析MapQuest反向地理编码api中的数据?

2024-04-25 15:29:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码:

from urllib import request
import json

lat = 31.33 ; long = -84.52

webpage = "http://www.mapquestapi.com/geocoding/v1/reverse?key=MY_KEY&callback=renderReverse&location={},{}".format(lat, long)

response = request.urlopen(webpage)
json_data = response.read().decode(response.info().get_param('charset') or 'utf-8')
data = json.loads(json_data)
print(data)

这给了我以下错误:

^{pr2}$

我试图从MapQuest反向地理编码api读取县和州。反应如下:

renderReverse({"info":{"statuscode":0,"copyright":{"text":"\u00A9 2015 MapQuest, Inc.","imageUrl":"http://api.mqcdn.com/res/mqlogo.gif","imageAltText":"\u00A9 2015 MapQuest, Inc."},"messages":[]},"options":{"maxResults":1,"thumbMaps":true,"ignoreLatLngInput":false},"results":[{"providedLocation":{"latLng":{"lat":32.841516,"lng":-83.660992}},"locations":[{"street":"562 Patterson St","adminArea6":"","adminArea6Type":"Neighborhood","adminArea5":"Macon","adminArea5Type":"City","adminArea4":"Bibb","adminArea4Type":"County","adminArea3":"GA","adminArea3Type":"State","adminArea1":"US","adminArea1Type":"Country","postalCode":"31204-3508","geocodeQualityCode":"P1AAA","geocodeQuality":"POINT","dragPoint":false,"sideOfStreet":"L","linkId":"0","unknownInput":"","type":"s","latLng":{"lat":32.84117,"lng":-83.660973},"displayLatLng":{"lat":32.84117,"lng":-83.660973},"mapUrl":"http://www.mapquestapi.com/staticmap/v4/getmap?key=MY_KEY&type=map&size=225,160&pois=purple-1,32.84117,-83.660973,0,0,|&center=32.84117,-83.660973&zoom=15&rand=-189494136"}]}]})

如何将此字符串转换为dict,以便使用键进行查询?任何帮助都将不胜感激。谢谢!在


Tags: keyimportcomjsonhttpdataresponserequest
1条回答
网友
1楼 · 发布于 2024-04-25 15:29:11

首先,去掉URL中的回调参数,因为这是导致响应被包装在renderReverse()中的原因

webpage = "http://www.mapquestapi.com/geocoding/v1/reverse?key=MY_KEY&location={},{}".format(lat, long)

这将为您提供有效的json,它应该与json.loads你调用的函数。此时,您可以像字典一样与数据交互,通过关键字获取县和州的名称。mapquests构造其json的方式非常奇怪,因此您可能需要进行一些字符串匹配才能获得正确的密钥名。在本例中,“adminArea4Type”设置为“country”,因此您希望访问“adminArea4”键以返回县名称。在

data['results'][0]['locations'][0]['adminArea4']

相关问题 更多 >