I have a simple code to fetch users from db using sqlalchemy and return them as json. My problem is how to format the output to get something like this:
{"results": [{"id":1, "username":"john"},{"id":2,"username":"doe"}]}
my code outputs an error which I cant seem to fix being a newbie in python:
d = []
for user in Users.query.all():
v = {}
for columnName in Users.__table__.columns.keys():
v[columnName] = getattr( user, columnName )
d.append( v )
return jsonify( d )
The code says:
ValueError: dictionary update sequence element #0 has length 11; 2 is required
Thanks.
Ah, now that your code has been pasted, I can see that the fundamental problem is indeed coming from
jsonify. The below workaround should be satisfactory.Replace
jsonifywithjson.dumps, and let me know if that doesn’t fix the problem.But if you’d prefer to use
flask.jsonify, then you should take a look at theflaskdocumentation. The argument tojsonifyshould be the same as the argument to any dict constructor — i.e. a dict or an iterable of tuples. So that’s the problem.