Flask-Json我如何将多个行作为json对象返回 [英] Flask-Json How do i return mutiple rows as json objects
问题描述
我有一个用户列,我正在尝试通过json和ajax将其所有数据输出到html文件中. 我能够从一行返回多个列. 但是我无法弄清楚如何返回并调用多行.
I have a users column and i am trying to output all of its data on an html file via json and ajax. i am able to return multiple columns from a single row. But i am unable to figure out how to return and call multiple rows.
这是我的代码,也是我尝试过的几条评论内容.
Here is my code and also a couple of commented thing i have tried.
@app.route('/test', methods=['POST', 'GET'])
def test():
#thisworks
works = user.query.filter_by(name = 'foo').first()
return jsonify(name = works.name, id = works.id)
#BELOW LINES DONT WORK
#st = user.query.all()
#for i in st:
#jsonify(id = st.id[i] , name = st.username[i])
还,我是否需要在jquery中使用for循环或字典中的字典来调用它??
Also , will i have to call this in jquery with a for loop or a dictionary inside a dictionary.?
请帮助我 谢谢.
推荐答案
此处的想法是在进行json化之前将所需的所有数据放入列表/数组中. 以您的示例为例:
The idea here is to put all the data you need in a list/array before you jsonify. Using your example:
st = user.query.all()
all_users = [{'name':user.name,'id':user.id} for user in st]
return jsonify(all_users)
希望这会有所帮助
要在jquery中使用结果,您可以执行以下操作
To use the results in jquery, you can do some thing like this
$.get('mysite.com/users').then(function(response) { // ajax to get users
users = response; // save to variable
$.each(users, function(key, val) { // iterate over result
console.log(val.id);
console.log(val.name)
});
});
这篇关于Flask-Json我如何将多个行作为json对象返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!