【问题标题】:How to append value of a JSON response in a list (python)?如何在列表(python)中附加 JSON 响应的值?
【发布时间】:2023-01-20 16:05:32
【问题描述】:

我收到来自 request.post() 的回复,如下所示:

{'total': 3,
 'files': [{'fileName': 'abc.mp4', 'size': '123'},
           {'fileName': 'def.mp4', 'size': '456'},
           {'fileName': 'ghi.mp4', 'size': '789'}]
}

我只想要此响应中的文件名值并将其存储在 str 列表中。

我尝试了以下循环来做同样的事情,但它显示了一些错误:

        fileNames = []
        for files in response.json()["files"]:
            fileNames.append(files["filename"])

我期待文件名列表,但出现了一些错误

【问题讨论】:

  • 你得到了什么错误? “一些错误”没有帮助。
  • 你得到了什么错误?发布完整的回溯。
  • 首先,你得到的错误是什么?其次,您要寻找的预期输出是什么?
  • 您收到 KeyError 是因为您忘记了字典键(当它们是字符串时)区分大小写

标签: python http


【解决方案1】:

尝试使用:

fileNames = []
        for files in response.json()["files"]:
            fileNames.append(files["fileName"])

我认为您写的是 filename 而不是 "fileName" (“名称”大写)。

【讨论】:

    猜你喜欢
    • 2022-11-29
    • 2019-04-30
    • 2014-01-04
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    相关资源
    最近更新 更多