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

3

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]'}
Hartebeest answered 12/5, 2014 at 3:22 Comment(3)
You need to serialize the results. look at this answer #7103254Dorn
marshmallow-sqlalchemy.readthedocs.io/en/latestLambdacism
To JSON serialize , here is my solution: #20172190Oligochaete
T
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
Tresatrescha answered 2/11, 2014 at 22:5 Comment(1)
Here's a gist that is up to date with marshmallow 1.0: gist.github.com/sloria/aecc540db3a95fbbee2fNeelon
A
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

Amphistylar answered 12/5, 2014 at 4:13 Comment(0)
C
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())
Canvasback answered 12/5, 2014 at 15:17 Comment(2)
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)Hartebeest
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.)Canvasback

© 2022 - 2024 — McMap. All rights reserved.