【问题标题】:Error accessing specific value from JSON file从 JSON 文件访问特定值时出错
【发布时间】:2019-12-28 06:15:50
【问题描述】:

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

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

这是我的代码:

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


    【解决方案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 变量附近有 []

    【讨论】:

    • 啊,我现在看到我的旧代码错误,感谢更新!我最终使用了你的代码。必须更容易理解,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2012-04-10
    • 1970-01-01
    相关资源
    最近更新 更多