Flask-Json How do i return mutiple rows as json objects

筅森魡賤 提交于 2019-12-25 18:12:33

问题


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])

Also , will i have to call this in jquery with a for loop or a dictionary inside a dictionary.?

Please do help me with this Thanks.


回答1:


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)

Hope this helps

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)
   });
});



回答2:


It looks like you want to build your data structure and then use jsonify on that. Something like:

# create a list of user ids and names
user_data = []
for user in user.query.all():
    user_data.append({
      'id': user.id,
      'name': user.name,
    })
 return jsonify(user_data)

There are several ways you could create that data structure, but this seems clear as an example.



来源:https://stackoverflow.com/questions/45523027/flask-json-how-do-i-return-mutiple-rows-as-json-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!