简体   繁体   中英

extracting particular values from JSON

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 )?

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"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM