python - 从 JSON 文件访问特定值时出错

标签 python json string integer typeerror

我正在尝试解析一些 JSON,并且需要提取某些值并将它们存储在 2D 列表中。但是,当我尝试保存单个值时,我不断收到类型错误。我也使用Python 3.6.8。

我尝试寻找几种不同的解决方案,例如将其转换为列表、整数和字符串。我还查看了以下链接:attempt1 , attempt2attempt3 。我相信错误来自于我尝试访问该值的方式。我尝试修改我的代码以使其正常运行,但我就是无法让它执行。

这是我的代码:

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

最佳答案

我不知道为什么要使用len()进行迭代,如果不需要的话,这段代码会给你你想要的,其中app变量是你的json

for chat in app['data']['chats']:
    for msg in chat['messages']:
        item = msg['sender']['id']
        print(item)

UPD1:您的版本如下所示:

j[["data"]["chats"][chat]["messages"][msg]["sender"]["id"]]
j["data"]["chats"][chat]['messages'][msg]['sender']['id']

如您所见 - j 变量附近有 []

关于python - 从 JSON 文件访问特定值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57617518/

相关文章:

java - 我们可以通过 URLConnection 传递多少数据?

javascript - 使用函数参数访问 JSON 数组 javascript

json - Swift: Hook Decodable.init() 以获得未指定的 key ?

c# - 如果在返回字符串的方法中找不到字符串,则返回替代值

Python re.sub 从一组中抓取单个字符

python - BeautifulSoup使用独特的CSS选择器

python - 使用 Python 抓取 .aspx 表单

python - ipyparallel 附加到列表的并行 for 循环

安卓动态字符串 : %1d vs %1$d

string - 在接口(interface)上使用 Into<String> - Vec<Into<String>> 的成本为零?