JSON TypeError: string indices must be integers

8 浏览
0 Comments

JSON TypeError: string indices must be integers

在以下代码中,我遇到了"TypeError: string indices must be integers"的错误。

import json
import requests
url = "https://petition.parliament.uk/petitions/300139.json"
response = requests.get(url)
data = response.text
parsed = json.loads(data)
sig_count = data["attributes"]["signature_count"]
print(sig_count)

0
0 Comments

JSON TypeError: string indices must be integers问题的出现原因是尝试在字符串上使用索引操作,而不是在JSON对象上进行操作。在使用json.loads()方法后,需要使用新定义的变量来访问JSON对象,因为该操作不是原地操作。变量"data"是以字符串形式解释的JSON数据。

解决方法是使用正确的变量来访问JSON对象。可以尝试使用以下代码:

parsed['attributes']['signature_count']

0
0 Comments

在这段代码中,首先导入了`json`模块,并定义了一个变量`url`,指向了一个JSON文件的URL地址。接下来,使用`requests`模块的`get`方法发送了一个GET请求,获取到了该URL地址对应的响应。然后,将响应的内容赋值给了变量`data`。

接着,使用`json`模块的`loads`方法将变量`data`中的内容解析为JSON格式,并将解析后的结果赋值给了变量`parsed`。之后,通过多层嵌套的索引,从`parsed`中获取了`data`、`attributes`和`signature_count`这三个键对应的值,并将结果赋值给了变量`sig_count`。

最后,使用`print`函数输出了变量`sig_count`的值。

然而,在这段代码中存在一个问题。问题的原因是在获取`parsed`中的值时,缺少了一个键`data`。因此,当执行到`parsed["data"]["attributes"]["signature_count"]`这一行时,会抛出`JSON TypeError: string indices must be integers`的异常。

为了解决这个问题,需要在获取`parsed`中的值时,添加缺少的键`data`。可以修改代码如下:

import json
import requests
url = 'https://petition.parliament.uk/petitions/300139.json'
response = requests.get(url)
data = response.text
parsed = json.loads(data)
sig_count = parsed["data"]["attributes"]["signature_count"]
print(sig_count)

通过添加缺少的键`data`,就可以正确地获取到`signature_count`的值,并成功输出。

0