Rob  P. Rob P. - 3 months ago 16
Python Question

python list of dictionaries

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.

Answer

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.

>>> import json
>>> json.dumps({"results": [{"id":1, "username":"john"},{"id":2,"username":"doe"}]})
'{"results": [{"username": "john", "id": 1}, {"username": "doe", "id": 2}]}'

Replace jsonify with json.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 the flask documentation. The argument to jsonify should be the same as the argument to any dict constructor -- i.e. a dict or an iterable of tuples. So that's the problem.

Comments