Reputation: 1413
I am using Google Distance Matrix API and the response I got was in JSON:
{
"destination_addresses" : [ "Chandigarh, India" ],
"origin_addresses" : [ "Delhi, India" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "244 km",
"value" : 243506
},
"duration" : {
"text" : "3 hours 54 mins",
"value" : 14069
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I want to get the following values from JSON, destination_address
, origin_address
, distance
, duration
, and status
. This is my code that I am trying out:
import requests as r
import json
a = r.get("https://maps.googleapis.com/maps/api/distancematrix/json?origins=Delhi&destinations=Chandigarh&key=key")
#text form of a
tfa = a.text
print(tfa)
with open('data.json','w') as outfile:
json.dump(tfa,outfile)
json_data = json.loads(tfa)
print(json_data["destination_addresses"])
print(json_data["origin_addresses"])
print(json_data["rows"][0]["elements"][0]["distance"])
print(json_data["rows"]["elements"]["duration"])
The output that I am receiving gives me destination origin and distance, but I get an error when I try to grab duration, also the values inside the distance
are printed as 'text':'244km','value':23432
, but I only want to get the values not their labels. Is there any way to do that? Also is it possible to limit the values extracted inside the distance
element (because I only want the text not the value)?
Upvotes: 0
Views: 54
Reputation: 1435
print(json_data["rows"][0]["elements"][0]["distance"]["value"])
Adding ["value"]
to your current code will only show the value.
print(json_data["rows"]["elements"]["duration"])
You try to get something from the same level as the distance but you forget the [0]
in this line. You can basically copy and paste the code that prints the distance value but replace distance
by duration
:
print(json_data["rows"][0]["elements"][0]["duration"]["value"])
Upvotes: 2