我正在使用Gmaps距离矩阵从给定的起始点和目的地获取值距离。
ddist = gmaps.distance_matrix (Origin, Destination)
得到这个结果:
{'status': 'OK', 'origin_addresses': ['Depok, Depok City, West Java, Indonesia'], 'rows': [{'elements': [{'status': 'OK', 'duration': {'value': 4366, 'text': '1 hour 13 mins'}, 'distance': {'value': 46143, 'text': '46.1 km'}}]}], 'destination_addresses': ['North Jakarta, North Jakarta City, Special Capital Region of Jakarta, Indonesia']}
我想从JSON上面提取['距离'] ['值']。
这就是我现在所拥有的:
for who in ddistt.keys():
ddist = json.loads(ddistt)
print('For %s: "value":' %who, ddist['rows']['element']['distance']['value'])
并返回此错误:
Traceback (most recent call last):
File "C:/src/distance.py", line 17, in <module>
ddist = json.loads(ddistt)
File "C:\Python35\lib\json\__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'dict'
如何解决?
答案 0 :(得分:1)
看起来返回的值已经是字典,因此您无需调用json.loads
。只是做:
>>> ddistt = {'status': 'OK', 'origin_addresses': ['Depok, Depok City, West Java, Indonesia'], 'rows': [{'elements': [{'status': 'OK', 'duration': {'value': 4366, 'text': '1 hour 13 mins'}, 'distance': {'value': 46143, 'text': '46.1 km'}}]}], 'destination_addresses': ['North Jakarta, North Jakarta City, Special Capital Region of Jakarta, Indonesia']}
>>> ddistt["rows"][0]["elements"][0]["distance"]["value"]
46143