How to return Sqlalchemy result as JSON?
-
20-06-2021 - |
Question
The Sqlalchemy result can have 0 to many records.
Result is:
record = meta.Session.query(model.EmpsTable).filter(model.EmpsTable
.firstname.like(searchQuery))
If there was only one record to return I would do:
return {'file_id':record.file_id, 'filename':
record.filename, 'links_to' :record.url}
I can print the records on terminal like such:
for r in record:
print r.file_id
But in this case I need to send these multiple records as JSON reply to a JQuery ajax.
How can I achieve this?
Solution
First thing, don't call record
an object that is a query, collection, instrumented sequence/whatever... then you can just get a list of dictionaries.
qry = meta.Session.query(model.EmpsTable).filter(model.EmpsTable
.firstname.like(searchQuery))
return {'data': [
{'file_id':record.file_id, 'filename':
record.filename, 'links_to' :record.url}
for record in qry
]}
To convert the returned object into JSON, you might already have decorated your method for that, or just call json.dumps() over it.
UPDATE: for security reasons, as pointed out by @MrGhimire it's better to wrap the list in a dictionary.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow