【发布时间】: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"]。