【问题标题】:Python gives TypeError while parsing request.dataPython 在解析 request.data 时给出 TypeError
【发布时间】:2020-03-02 12:00:32
【问题描述】:

从我的 React 应用程序中,我通过我的 Django API 的后端获取以下 Json。

{'0': {'title': 'The Title?', 'text': 'rdhdrhdr'}, '1': {'title': 'The Title2', 'text': 'hdrhdhdrh'}}

然后我尝试通过 for 循环迭代一些数据,

def post(self, request):
    data = request.data
    print(data)
    for a in data:
       print(a['title'])

在我希望它打印 Title 和 Title2 的地方,我收到以下错误。

    print(a['title'])
TypeError: string indices must be integers

我认为我的 json 有问题.. 但无法弄清楚。

【问题讨论】:

  • 1.您的数据不是 JSON,而是 Python 字典。 2. 在执行for a in data: 时,您正在迭代 keys 而不是数据。

标签: python json for-loop


【解决方案1】:

您正在迭代字典的键,而不是数据。你想做的是:

def post(self, request):
    data = request.data
    print(data)
    for a in data.values():
       print(a['title'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    • 2019-04-17
    • 2021-12-28
    • 2015-10-21
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    相关资源
    最近更新 更多