6

Basically, I just want to json encode the results of my sql query.

x = db.session.query(User).filter_by(username = request.form['username'], password = request.form['password']).first()
  print vars(x)
return jsonify(x)

raise TypeError(repr(o) + " is not JSON serializable")

TypeError: < User WashingtonGeorge> is not JSON serializable

Here is the result for the print vars(x)

{'_updated': None, 'username': u'WashingtonGeorge', 'password': u'Washington', '_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x7fd12a50c8d0>, 'firstname': u'George', 'lastname': u'Washington', '_created': None, 'fullname': u'George Washington', '_id': 1, 'email': u'[email protected]'}
3

3 Answers 3

5

You can use marshallow. Here is the example. define a serializer.py and put it beside your main.py file, and:

in serializer.py

from marshmallow import Serializer

###### USER SERIALIZER #####
class UserSerializer(Serializer):
    class Meta:
        # Fields to expose
        fields = ('username')
        # you can add any other member of class user in fields

#Return the user data in json format
def get_user_serialized(user):
    return UserSerializer(user).data

in your main.py

from .serializers import get_user_serialized
...
...
...

x = db.session.query(User).filter_by(username = request.form['username'], password = request.form['password']).first()

serialized = [get_user_serialized(item) for item in x]
res = jsonify(res=serialized)
return res
Sign up to request clarification or add additional context in comments.

1 Comment

Here's a gist that is up to date with marshmallow 1.0: gist.github.com/sloria/aecc540db3a95fbbee2f
1

With JSON serialize you can do that.

Look this: http://prschmid.blogspot.com/2012/12/json-serializing-sqlalchemy-objects.html

it work for me

Comments

0

I assume the variable '_updated' & '_created' in your class User are of type DateTime. Datetime is not serilzable in jsonify. You can just convert your datetime variable into str. i.e. str(some_date_in_datetimeformat) might work.
Also, '_sa_instance_state' which is of type sqlalchemy.orm.state.InstanceState should be serializable.

Update:

jsonify is not able to serialize your object. The best solution is to define a function serialize() inside your class and use it to make the data serializable. So your class becomes,

class User(object):
    def serialize():
        return {
            '_id': 1,
            'username': u'WashingtonGeorge'
            'fullname': u'George Washington'
            # other fields that you need in the json 
        }

then at the place where you want to jsonify the data, just call.

jsonify(x.serialize())

2 Comments

I tried delecting the attributes which contained datetime fields and the method you suggested didn't work. results = db.session.query(User).filter_by(username = request.form['username'], password = request.form['password']).first() del results._created del results._updated print vars(results) return jsonify(results = results)
I updated my answer. This is a common problem with jsonify, and has been answered before on stackoverflow (See codegeek's comment on your question.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.