json_util provides two helper methods, dumps and loads, that wrap the native json methods and provide explicit BSON conversion to and from json.
from bson.json_util import loads, dumps
record = db.movies.find_one()
json_str = dumps(record)
record2 = loads(json_str)
if record is:
{
"_id" : ObjectId("5692a15524de1e0ce2dfcfa3"),
"title" : "Toy Story 4",
"released" : ISODate("2010-06-18T04:00:00Z")
}
then json_str becomes:
{
"_id": {"$oid": "5692a15524de1e0ce2dfcfa3"},
"title" : "Toy Story 4",
"released": {"$date": 1276833600000}
}
It is possible to customize the behavior of dumps via a JSONOptions object. Two sets of options are already available: DEFAULT_JSON_OPTIONS and STRICT_JSON_OPTIONS.
>>> bson.json_util.DEFAULT_JSON_OPTIONS
JSONOptions(strict_number_long=False, datetime_representation=0,
strict_uuid=False, document_class=dict, tz_aware=True,
uuid_representation=PYTHON_LEGACY, unicode_decode_error_handler='strict',
tzinfo=<bson.tz_util.FixedOffset object at 0x7fc168a773d0>)
To use different options, you can:
modify the DEFAULT_JSON_OPTIONS object. In this case, the options will be used for all subsequent call to dumps:
from bson.json_util import DEFAULT_JSON_OPTIONS
DEFAULT_JSON_OPTIONS.datetime_representation = 2
dumps(record)
specify a JSONOptions in a call to dumps using the json_options parameter:
# using strict
dumps(record, json_options=bson.json_util.STRICT_JSON_OPTIONS)
# using a custom set of options
from bson.json_util import JSONOptions
options = JSONOptions() # options is a copy of DEFAULT_JSON_OPTIONS
options.datetime_representation=2
dumps(record, json_options=options)
The parameters of JSONOptions are:
{"$numberLong": "<number>" }. Otherwise they will be encoded as an int. Defaults to False.{"$date": <dateAsMilliseconds>}, 1 => {"$date": {"$numberLong": "<dateAsMilliseconds>"}}, 2 => {"$date": "<ISO-8601>"}{"$uuid": "<hex>" }. Defaults to False.datetime.tzinfo subclass that specifies the timezone from which datetime objects should be decoded. Defaults to utc.