0

The variable data has the following JSON

{
   "destination_addresses" : [ "Stade Leopold Sedar Senghor, Route de Yoff, Dakar, Senegal" ],
   "origin_addresses" : [ "Unnamed Road, Dakar, Senegal" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "13.0 km",
                  "value" : 13007
               },
               "duration" : {
                  "text" : "23 mins",
                  "value" : 1383
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

I then run the following code:

parsed =  json.loads(data)

I want to store distance "text" and "value", and duration "text" and "value" and "status" into variables in python. I tried the following code but it did not work:

dist = int(parsed['rows']['elements']['distance']['value'])

But I am getting an error

3
  • [] are lists, {} are dicts. Commented May 28, 2015 at 11:20
  • 2
    What is the error that you are getting? Commented May 28, 2015 at 11:21
  • @shruti1810, probably a TypeError: list indices must be integers, not str Commented May 28, 2015 at 11:25

2 Answers 2

3

The keys rows and elements are lists, so you'll need to specify an index:

dist = int(parsed['rows'][0]['elements'][0]['distance']['value'])
Sign up to request clarification or add additional context in comments.

Comments

0

Here you have working code. I have just changed a bit and it works fine. The access to dictionary it a little bit confusing. I will try to explain. The json.dumps serialize a str to a json obj. Here for more information. json.dumps

 data ={
   "destination_addresses" : [ "Stade Leopold Sedar Senghor, Route de Yoff, Dakar, Senegal" ],
   "origin_addresses" : [ "Unnamed Road, Dakar, Senegal" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "13.0 km",
                  "value" : 13007
               },
               "duration" : {
                  "text" : "23 mins",
                  "value" : 1383
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}


data_string = json.dumps(data)
parsed =  json.loads(data_string)

print parsed['rows'][0]['elements'][0]['distance']['text']

When you have a list into a dictionary first of all you have to refer the index(an integer) that you want to access and then the dictionary index with the name('string'). As you can see in the last line of the code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.