[英]TypeError: string indices must be integers with flask json
我正在測試需要在其中發布一些鍵值對的Flask應用程序,但是我的Flask應用程序期望它們采用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]
您需要傳入dict
list
,因為您的代碼嘗試處理dict
列表。 問題與json無關,而恰恰是您在數據結構中的讀取方式。 這是將您的代碼作為單個腳本演示的問題。 為了避免與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]
運行此結果
'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']
將會失敗。 從代碼的外觀來看,您似乎想從作為輸入的字典列表中創建字典列表。 並且一旦將輸入字典放入列表中,它就會崩潰……因為字典沒有您要求的鍵...但是更接近!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.