简体   繁体   English

TypeError:字符串索引必须是flask json的整数

[英]TypeError: string indices must be integers with flask json

I am testing a flask app where I need to post some key value pairs, but my flask app is expecting them in JSON format. 我正在测试需要在其中发布一些键值对的Flask应用程序,但是我的Flask应用程序期望它们采用JSON格式。 At the command line I created json from my kv pairs like so: 在命令行中,我从kv对创建了json,如下所示:

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

when I put this into postman: 当我把这个放进邮递员时:

在此处输入图片说明

and post it to my app I get: 并将其发布到我的应用程序中,我得到:

TypeError: string indices must be integers

However if I use: 但是,如果我使用:

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

It works! 有用! Why is this happening? 为什么会这样呢?

Here is the app code. 这是应用程序代码。 the error is happening at the last line: 错误发生在最后一行:

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]

You need to pass in a list of dict s because your code tries to process a list of dicts. 您需要传入dict list ,因为您的代码尝试处理dict列表。 The problem isn't related to json, that just happens to be how you read in the data structure. 问题与json无关,而恰恰是您在数据结构中的读取方式。 Here's your code as a single script demonstrating the problem. 这是将您的代码作为单个脚本演示的问题。 I changed the name to data to avoid confusion with json and I'm using repr instead of str to keep the problem clear. 为了避免与json混淆,我将名称更改为data ,并且我使用了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]

Running this results in 运行此结果

'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

Your print statement shows that iterating through data produces strings so it makes sense that j['token'] will fail. 您的打印语句表明,遍历data会产生字符串,因此j['token']将会失败。 From the looks of your code, it seems like you want to create a list of dicts from a list of dicts as input. 从代码的外观来看,您似乎想从作为输入的字典列表中创建字典列表。 And once you put the input dicts in a list, it ... well crashes because the dicts don't have the keys you claim... but is closer! 并且一旦将输入字典放入列表中,它就会崩溃……因为字典没有您要求的键...但是更接近!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM