Reputation: 195
I am using Gmaps Distance Matrix to get a value distance from given point of origin and destination.
ddist = gmaps.distance_matrix (Origin, Destination)
and get this result:
{'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']}
I want to extract ['distance']['value'] from above JSON.
This is what I have for now:
for who in ddistt.keys():
ddist = json.loads(ddistt)
print('For %s: "value":' %who, ddist['rows']['element']['distance']['value'])
And return to this error:
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'
How to fix it?
Upvotes: 0
Views: 932
Reputation: 52223
It looks like the returned value is already a dictionary so you don't need to call json.loads
. Just do:
>>> 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
Upvotes: 1