Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h1>Updated for 2018</h1> <p>The original answer accommodated the way MongoDB "date" fields were represented as:</p> <p><code>{"$date": 1506816000000}</code></p> <p>If you want a generic Python solution for serializing <code>datetime</code> to json, check out <a href="https://stackoverflow.com/a/36142844/293064">@jjmontes' answer</a> for a quick solution which requires no dependencies.</p> <hr> <p>As you are using mongoengine (per comments) and pymongo is a dependency, pymongo has built-in utilities to help with json serialization:<br> <a href="http://api.mongodb.org/python/1.10.1/api/bson/json_util.html" rel="noreferrer">http://api.mongodb.org/python/1.10.1/api/bson/json_util.html</a></p> <p>Example usage (serialization):</p> <pre><code>from bson import json_util import json json.dumps(anObject, default=json_util.default) </code></pre> <p>Example usage (deserialization):</p> <pre><code>json.loads(aJsonString, object_hook=json_util.object_hook) </code></pre> <hr> <h2>Django</h2> <p>Django provides a native <code>DjangoJSONEncoder</code> serializer that deals with this kind of properly.</p> <p>See <a href="https://docs.djangoproject.com/en/dev/topics/serialization/#djangojsonencoder" rel="noreferrer">https://docs.djangoproject.com/en/dev/topics/serialization/#djangojsonencoder</a></p> <pre><code>from django.core.serializers.json import DjangoJSONEncoder return json.dumps( item, sort_keys=True, indent=1, cls=DjangoJSONEncoder ) </code></pre> <p>One difference I've noticed between <code>DjangoJSONEncoder</code> and using a custom <code>default</code> like this:</p> <pre><code>def default(o): if type(o) is datetime.date or type(o) is datetime.datetime: return o.isoformat() return json.dumps( item, sort_keys=True, indent=1, default=default ) </code></pre> <p>Is that Django strips a bit of the data:</p> <pre><code> "last_login": "2018-08-03T10:51:42.990", # DjangoJSONEncoder "last_login": "2018-08-03T10:51:42.990239", # default </code></pre> <p>So, you may need to be careful about that in some cases.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload