2017-07-25 60 views
0

我对Flask和Python很新,我必须将MySql查询转换为json格式。 关于转换,我面临价值错误,无法理解,请帮助我,谢谢你提前。jsonify上的ValueError

ValueError: dictionary update sequence element #0 has length 8; 2 is required on executing jsonify(r)

@app.route('/post') 
def display(): 
    cursor.execute("select * from tablename") 
    result=cursor.fetchall() 
    r = [dict((cursor.description[i][0], value) for i, value in enumerate(row)) for row in result] 
return jsonify(r) 
+0

如果删除列表中的括号并只是一个字典,该怎么办? –

+0

你使用什么版本的烧瓶? –

回答

0

有更好的方法来创建从MySQL查询字典,这将让你身边,你遇到的错误。

当你定义你的光标,你应该有它返回的查询结果词典列表,像这样:

cursor = connection.cursor(dictionary=True)

这样,你的表的每一行是从查询返回会作为列表中的字典存在。这将是这个样子:

[ 
    {'firstcol': 'value1row1', 'secondcol': 'value2row1'... 'tenthcol': 'value10row1'}, 
    {'firstcol': 'value1row2', 'secondcol': 'value2row2'... 'tenthcol': 'value10row2'}, 
    ... 
    {'firstcol': 'value1row50', 'secondcol': 'value2row50'... 'tenthcol': 'value10row50'} 
] 

然后,jsonifying你的结果变得很轻松:

return jsonify(result)

从那里,你将有可通过钥匙引用元素JSON对象。如果要显示'firstcol'中的所有值,则只需在您的JavaScript文件中使用response['firstcol']

此外,为了确保您明确了Flask路由,标题为'/ post'的路由没有为您的路由定义'POST'方法。你需要:

@app.route('/post' methods=['POST'])

我道歉,如果你已经意识到了这一点 - 我刚开始学习瓶几个月前,最初非常困惑的一些约定,所以我想你可能是和我在同一条船上。

0

您正在使用旧版本的Flask。 0.12改变了jsonify以允许任何类型,以前只允许元组的列表和列表被允许。

pip install -U flask