TypeError:在解析json时,list indices必须是整数,而不是str

时间:2022-08-14 19:36:48

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

提交请求后,我收到了以下json:

{"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,

我在变量j中捕获了响应并加载如下,

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?

我究竟做错了什么?

2 个解决方案

#1


8  

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

l ['type']为您提供一个列表,而不是一个对象。所以你必须像列表一样访问它

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

#2


1  

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

密钥类型的值是列表。尝试做类型(l ['type'])来确认。

To access that value you would need to use:

要访问该值,您需要使用:

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

升[ '类型'] [0] [ '的引用']

which would give you another list.

哪个会给你另一个清单。

#1


8  

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

l ['type']为您提供一个列表,而不是一个对象。所以你必须像列表一样访问它

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

#2


1  

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

密钥类型的值是列表。尝试做类型(l ['type'])来确认。

To access that value you would need to use:

要访问该值,您需要使用:

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

升[ '类型'] [0] [ '的引用']

which would give you another list.

哪个会给你另一个清单。