Rishabh Kandari
Rishabh Kandari

Reputation: 160

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

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.

Upvotes: 1

Views: 6217

Answers (3)

Siri
Siri

Reputation: 29

The first import these, from marshmallow_sqlalchemy import SQLAlchemySchema, SQLAlchemyAutoSchema, auto_field

I hope you have already sqlalchemy and create a table User

class User(Base):
__tablename__="User"
ID=Column('ID',INTEGER, primary_key=true)
username=Column('Username',NVARCHAR(255))
......

and create a class for your table (use marshmallow)

class User_Schema(SQLAlchemyAutoSchema):
class Meta:
    model = User
    include_relationships = True
    load_instance = True

and declare global variable

all_rows=[]                              //declaring a global variable

and then inside your route

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

all_rows.clear() //you need to clear first
Rowdata=user.query.all()                  //Receiving all row data

for every_row in Rowdata:
    row= User_Schema.dump(every_row) //jsonifying every row
    all_rows.append(row)                  //adding to the json table
return jsonify(all_rows)

Upvotes: 0

sea
sea

Reputation: 319

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

Upvotes: 4

Rob
Rob

Reputation: 7717

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.

Upvotes: 2

Related Questions