【问题标题】:TypeError: string indices must be integers with flask jsonTypeError:字符串索引必须是带有flask json的整数
【发布时间】:2015-12-03 18:53:52
【问题描述】:

我正在测试一个烧瓶应用程序,我需要在其中发布一些键值对,但我的烧瓶应用程序期望它们采用 JSON 格式。在命令行中,我从我的 kv 对创建了 json,如下所示:

>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True,indent=4, separators=(',', ': '))
{
    "4": 5,
    "6": 7
}

当我把它放入邮递员时:

并将其发布到我得到的应用程序中:

TypeError: string indices must be integers

但是,如果我使用:

[{
    "4": 5,
    "6": 7
}]

有效!为什么会这样?

这是应用程序代码。错误发生在最后一行:

json = request.get_json(force=True) # receives request from php
for j in json:
        print str(j)

test = [{'ad': j['4'], 'token':j['6']} for j in json]

【问题讨论】:

  • 问题是j['4'] 其中j 是一个字符串。请改用j[4]。你明白j 是 JSON 对象中的最后一个键吗?如果j 的值为"4",则j[4] 也会失败,但会出现IndexError。你可能想要json[0]["4"]

标签: python json flask


【解决方案1】:

您需要传入dicts 中的list,因为您的代码会尝试处理字典列表。问题与 json 无关,这恰好是您在数据结构中读取的方式。这是您的代码作为单个脚本演示问题。我将名称更改为data 以避免与json 混淆,并且我使用repr 而不是str 以保持问题清晰。

data = {'4': 5, '6': 7}

for j in data:
        print repr(j)

test = [{'ad': j['ad'], 'token':j['token']} for j in data]

运行这个结果

'4'
'6'
Traceback (most recent call last):
  File "x.py", line 6, in <module>
    test = [{'ad': j['ad'], 'token':j['token']} for j in data]
TypeError: string indices must be integers, not str

您的打印语句显示遍历data 会产生字符串,因此j['token'] 将失败是有道理的。从您的代码的外观来看,您似乎想从一个 dicts 列表中创建一个 dicts 列表作为输入。而且,一旦您将输入的 dicts 放入一个列表中,它...就会崩溃,因为 dicts 没有您声称的键...但是更接近!

【讨论】:

猜你喜欢
  • 2018-05-15
  • 2020-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-22
  • 1970-01-01
相关资源
最近更新 更多