olleh
olleh

Reputation: 1277

Python Sql Alchemy - How to jsonify a class object result from a database query

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]'}

Upvotes: 6

Views: 15497

Answers (3)

Nima Soroush
Nima Soroush

Reputation: 12814

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

Upvotes: 5

Nitin Nain
Nitin Nain

Reputation: 5483

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())

Upvotes: 0

yograterol
yograterol

Reputation: 603

With JSON serialize you can do that.

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

it work for me

Upvotes: 1

Related Questions