How to serialize the result of a query in python?
Question: I'm having trouble to serialize the result array from a query where one of its
projection is of datetime property.

My model class looks as follows:

    
    
    class ActivitySummaries(ndb.Model):
        registered_users = ndb.IntegerProperty()
        activated_users = ndb.IntegerProperty()
        company_registered = ndb.IntegerProperty()
        broker_registered = ndb.IntegerProperty()
        investor_registered = ndb.IntegerProperty()
        deal_approved = ndb.IntegerProperty()
        broker_approved = ndb.IntegerProperty()
        investor_approved = ndb.IntegerProperty()
        company_searched = ndb.IntegerProperty()
        broker_searched = ndb.IntegerProperty()
        investor_searched = ndb.IntegerProperty()
        watchlisting = ndb.IntegerProperty()
        closed_deals = ndb.IntegerProperty()
        timestamp = ndb.DateTimeProperty(auto_now_add=True)
    
    Query:
    
    activities = cls.query()
    

**I want to send the the result array of the query in serialized form from
Python using JSON and de-serialize in JavaScript using JSON.**

I'm getting the following error:

    
    
    raise TypeError(repr(o) + " is not JSON serializable")
    TypeError: ActivitySummaries(key=Key('ActivitySummaries', 923), activated_users=0, broker_approved=0, broker_registered=0, broker_searched=1, closed_deals=0, company_registered=0, company_searched=1, deal_approved=0, investor_approved=0, investor_registered=0, investor_searched=0, registered_users=0, timestamp=datetime.datetime(2013, 5, 21, 22, 14, 28, 48000), watchlisting=0) is not JSON serializable
    

So I tried to use a subclass to handle the arbitrary value which is as
follows:

    
    
    import datetime
    from json import JSONEncoder
    
    class DateEncoder(JSONEncoder):
        def default(self, obj):
            if isinstance(obj, datetime.date):
                return obj.isoformat()
            return JSONEncoder.default(self, obj)
    

And call it using `json.dumps(data, cls=DateEncoder)`

But I still get the same error.

I have read somewhere that NDB Class has to_dict() built in method which we
would normally call and then serialize the dictionary. Can any one help me out
to serialize for this particular instance using to_dict(). I can provide you
more details of the code if necessary.

**P.S : My project is not using "Django" or "simplejson".**


Answer: Many options elsewhere. One of them, from
<http://blog.codevariety.com/2012/01/06/python-serializing-dates-datetime-
datetime-into-json/>:

    
    
    def date_handler(obj):
        return obj.isoformat() if hasattr(obj, 'isoformat') else obj
    
    print json.dumps(data, default=date_handler)
    

Note than in your example, you should have used 'default=' instead of 'cls='.

