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.
In Python, we can have a list or an array of dictionaries. In such an object, every element of a list is a dictionary. Every dictionary can be accessed using its index.
Lists are mutable data types in Python. Lists is a 0 based index datatype meaning the index of the first element starts at 0. Lists are used to store multiple items in a single variable. Lists are one of the 4 data types present in Python i.e. Lists, Dictionary, Tuple & Set.
I solved this error by simply saying
return jsonify( results = d )
instead of
return jsonify( d )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With