python 解析json typeerror,Python:解析JSON时出现Keyerror

I have just made a program to parse some data from an api.

The api gives data back with a JSON format. When I try to parse it it gives me a key error

Traceback (most recent call last):

File "test.py", line 20, in

print(parsed_json['plain'])

KeyError: 'plain'

This is the part of the code that matters (the rest is just for making the url, works perfectly fine)

response = urllib.request.urlopen(url2).read()

strr = str(response)

if "plain" in strr:

parsed_json = json.loads(response.decode("UTF-8"))

print(parsed_json['plain'])

elif "INVALID HASH" in strr:

print("You have entered an invalid hash.")

elif "NOT FOUND" in strr:

print("The hash is not found")

elif "LIMIT REACHED&#

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 当Python读取JSON文件,可能会出现TypeError: string indices must be integers”的错误。这是因为使用了字典或列表的字符串索引进行访问,而字符串索引必须是整数。 例如,当使用以下代码读取JSON文件: import json with open('example.json', 'r') as f: data = json.loads(f.read()) print(data['name']) 如果JSON文件中的数据形式为: { "name": "John Doe", "age": 25, "address": { "street": "123 Main St.", "city": "Anytown", "state": "CA", "zip": "12345" } } 则运行代码后会出现TypeError: string indices must be integers”的错误,因为我们使用字符串索引“name”进行访问。正确的访问方式应该是使用数据的数字索引/键值,例如: print(data['age']) # 使用数字索引 print(data['address']['city']) # 使用键值 要避免这个错误,需要确保使用字典或列表的整数索引进行访问。可以在读取JSON文件之前查看文件内容,以确保使用正确的键值和索引。 ### 回答2: 当我们使用Python读取一个JSON文件,看到这个错误身,这个错误通常是因为尝试在字符串上使用整数索引而引起的。这意味着我们在代码中使用了下标而不是key来访问JSON对象的值。 JSON文件中只有键值对,而且值可以是任何类型。当我们需要访问值,需要使用相应的键名。如果我们尝试使用整数索引,则会出现上述错误。 解决这个问题的方法是检查你的代码中是否在JSON对象中使用了下标而非key。如果是这样,我们应该根据JSON的结构使用正确的键名来访问该对象。 另外,我们还可以使用Python内置的JSON模块来处理JSON文件。JSON模块可以方便地将JSON格式的数据转换为Python中的字典格式,然后我们可以轻松地访问和操作其中的键值对。 总之,出现"TypeError: string indices must be integers"的错误通常是因为我们尝试使用下标而不是key访问JSON对象的值。通过使用正确的键来访问JSON对象,可以轻松地解决这个问题。 ### 回答3: 这个错误出现的原因是因为读取的json文件被解析成为了字符串,而不是json格式。这就导致了程序在读取字符串的候无法将其索引,从而报错。 要解决这个问题,需要在读取json文件的候,使用json模块将其解析成为json格式。具体的步骤如下: 1. 使用python内置的open函数打开json文件,读取文件内容; 2. 运用json模块中的load函数将文件内容解析成为json格式; 3. 对解析后的json格式进行遍历访问和操作。 举个例子,假如我们有以下的json格式文件"data.json": { "name": "John", "age": 25, "city": "New York" } 我们可以使用以下的代码来读取和解析文件,遍历所有的数据: import json with open('data.json', 'r') as f: data = json.load(f) print(data['name']) # 输出 'John' print(data['age']) # 输出 25 print(data['city']) # 输出 'New York' 这样,我们就成功地将json文件读取并解析出来了,避免了"typeerror: string indices must be integers"错误的出现。需要注意的是,在读取json文件,文件路径和名称要正确,避免读取出错或文件不存在的情况。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值