Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: list indices must be integers, not str,while parsing json

Tags:

python

json

After submitting a request I have received the following json back:

{"type": [
{"ID": "all", "count": 1, "references": [
    { "id": "Boston,MA,02118", "text": "Boston,MA,02118", "val": "Boston,MA,02118", "type": 1 ,"zip": "02118","city": "Boston","state": "MA","lt": "42.3369","lg": "-71.0637","s": ""}
] }
] } 

I captured the response in variable j and loaded it as follows,

l = json.loads(j)

Now I have:

>>> type(l)
<type 'dict'>
>>> l['type']['references']
Traceback (most recent call last):
  File "C:\PyCharm\helpers\pydev\pydevd_exec.py", line 3, in Exec
    exec exp in global_vars, local_vars
  File "<input>", line 1, in <module>
TypeError: list indices must be integers, not str

What am I doing wrong?

like image 817
user1592380 Avatar asked Aug 03 '14 14:08

user1592380


2 Answers

l['type'] gives you a list, not an object. So you have to access it like a list

l['type'][0]["references"]
like image 184
Salem Avatar answered Nov 19 '22 09:11

Salem


The value of the key type is a list. Try doing type(l['type']) to confirm.

To access that value you would need to use:

l['type'][0]['references']

which would give you another list.

like image 43
kylieCatt Avatar answered Nov 19 '22 09:11

kylieCatt