2

I have a json that looks like this:

[  
   {  
      "status":"passed",
      "elements":[{"name":"foo"},{"name":"bar"}]
   },
   {  
      "status":"failed",
      "elements":[{"name":"foo1"},{"name":"bar1"}]
   }
]

I am trying to iterate through the elements array:

for a in json['elements']:
   print a['name']

I get this error:

TypeError: list indices must be integers, not str

My python is really bad. Thank you

1
  • json['elements'] gives you a list of two items: {"name":"foo1"}, and {"name":"bar1"}, so you need to index into it with an integer, not a string. Commented Dec 29, 2016 at 16:06

3 Answers 3

2

Try this:

for a in json:
   for b in a['elements']:
       print b['name']
Sign up to request clarification or add additional context in comments.

1 Comment

BTW, your data structure is not a JSON, it's an array of JSONs.
0

With your code, you are trying to get the value of the key 'elements' from the dictionary json. But json isn't a dict, but an array of dicts. Thus, what you should do instead is:

for dic_x in json:
    for dic_y in dic_x['elements']:
        print dic_y['name']

Comments

0

You need to loop through your list and then proceed with your data like what you do with dicts like this example:

my_json = [  
   {  
      "status":"passed",
      "elements":[{"name":"foo"},{"name":"bar"}]
   },
   {  
      "status":"failed",
      "elements":[{"name":"foo1"},{"name":"bar1"}]
   }
]

for element in my_json:
    for v in element["elements"]:
        print(v["name"])

Output:

foo
bar
foo1
bar1

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.