title: How to serialize the result of a query in python?
body: <p>I'm having trouble to serialize the result array from a query where one of its projection is of datetime property.</p>
  
  <p>My model class looks as follows: </p>
  
  <pre><code>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()
  </code></pre>
  
  <p><strong>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.</strong></p>
  
  <p>I'm getting the following error:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>So I tried to use a subclass to handle the arbitrary value which is as follows:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>And call it using <code>json.dumps(data, cls=DateEncoder)</code></p>
  
  <p>But I still get the same error.</p>
  
  <p>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>
  
  <p><strong>P.S : My project is not using "Django" or "simplejson".</strong> </p>