【发布时间】:2019-12-28 06:15:50
【问题描述】:
我正在尝试解析一些 JSON,我需要提取某些值并将它们存储在 2D 列表中。但是,当我尝试保存单个值时,我不断收到 TypeError。我也在使用 Python 3.6.8。
我尝试了几种不同的解决方案,例如将其转换为列表、整数和字符串。我还查看了以下链接:attempt1、attempt2 和 attempt3。我相信错误来自我尝试访问该值的方式。我试图玩弄我的代码以使其正常运行,但我就是无法让它执行。
这是我的代码:
with open('../data.json') as json_data:
j = json.load(json_data)
json_data.close()
for chat in range(len(j["data"]["chats"])):
temp = []
for msg in range(len(j["data"]["chats"][chat]["messages"])):
item = j[["data"]["chats"][chat]["messages"][msg]["sender"]["id"]]
print(item)
这是我的一些 JSON:
{
"application":"HelloWorld",
"data":{
"chats":[
{
"name":"max",
"parties":[
{
"id":"1"
},
{
"id":"2"
}
],
"messages":[
{
"sender":{
"id":"1"
},
"id":"1234",
"content":[
{
"data":"Hello number 2",
"type":"txt"
}
],
"timestamp":{
"created":816080400
}
},
聊天部分重复 4 次,消息项在每个聊天中重复几次,然后发件人项在每个消息项中重复几次。
目前我的代码只是在该行抛出一个错误:
item = j[["data"]["chats"][chat]["messages"][msg]["sender"]["id"]]
错误是:
Traceback (most recent call last):
File "main.py", line 14, in <module>
item = j[["data"]["chats"][chat]["messages"][msg]["sender"]["id"]]
TypeError: list indices must be integers or slices, not str
我想做的是成功打印该值,因此会发生以下情况:
print(item)
#Will print:1
【问题讨论】:
标签: python json string integer typeerror