Rob  P.
Rob P.

Reputation: 401

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.

Upvotes: 8

Views: 5846

Answers (4)

Croo
Croo

Reputation: 1371

I solved this error by simply saying

return jsonify( results = d )

instead of

return jsonify( d )

Upvotes: 10

DNA
DNA

Reputation: 42607

The error is what you'd expect when creating a dict incorrectly - see Python dictionary creation error

Edited: See answer from senderle that identifies the root cause...

Upvotes: 0

senderle
senderle

Reputation: 151007

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.

Upvotes: 7

Keith
Keith

Reputation: 43024

You're calling dict() with *args, which is going to expand args to positional parameters. That is a typical cause of that error you are seeing. Leave that out.

Upvotes: 0

Related Questions