Indexes of type Error: list must be integers, not str, when parsing json

After sending the request, I 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 grabbed the answer in j variable and loaded it like this:

 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?

+6
source share
2 answers

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

 l['type'][0]["references"] 
+7
source

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

To access this value, you need to use:

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

which will give you another list.

+1
source

Source: https://habr.com/ru/post/973279/


All Articles