字符串索引必须是带有JSON的整数

字符串索引必须是带有JSON的整数

本文介绍了TypeError:字符串索引必须是带有JSON的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试一个烧瓶应用程序,我需要发布一些关键值对,但我的烧瓶应用程序正在期待他们在JSON格式。在命令行我创建了json从我的kv对像这样:

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

这变成邮递员:





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

$ p $ TypeError:字符串索引必须是整数



$ p $ [{
4:5,
6:7
}]

有用!为什么会发生这种情况?



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

$ $ p $ json = request.get_json(force = True)#接收来自php $ b的请求$ b为j在json中:
print str(j)

test = [{'ad':j ['4'],'token':j ['6']}对于j中的json]


解决方案

list dict s因为你的代码试图处理一个列表的列表。这个问题与json无关,恰好是你在数据结构中读取的方式。这是您的代码作为演示问题的单个脚本。为了避免与 json 混淆,我将名称改为 data ,并使用 repr 而不是 str 来清除问题。

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

for data in data:
print repr(j)

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



$ p


$ b $ 6 $

$ b $ p $ (最近的最后一次调用):
在< module>文件中的第6行x.py
test = [{'ad':j ['ad'],'token':j ['token']} for data in data]
TypeError:字符串索引必须是整数,而不是str

您的print语句显示迭代 data 产生字符串,所以 j ['token'] 将会失败。从你的代码的外观看,你似乎想创建一个列表中的字典列表作为输入。而且一旦你把输入的字典放在一个列表中,它就会崩溃,因为这些字典没有你要求的密钥...但是更接近!

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. At the command line I created json from my kv pairs like so:

>>> 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 dicts because your code tries to process a list of dicts. The problem isn't related to json, that just happens to be how you read in the data structure. 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.

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. 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!

这篇关于TypeError:字符串索引必须是带有JSON的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:36