JSON TypeError: string indices must be integers
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)
在这段代码中,首先导入了`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`的值,并成功输出。