json_util – Tools for using Python’s json module with BSON documents

Tools for using Python’s json module with BSON documents.

This module provides two helper methods dumps and loads that wrap the native json methods and provide explicit BSON conversion to and from json. This allows for specialized encoding and decoding of BSON documents into Mongo Extended JSON‘s Strict mode. This lets you encode / decode BSON documents to JSON even when they use special BSON types.

Example usage (serialization):

>>> from bson import Binary, Code
>>> from bson.json_util import dumps
>>> dumps([{'foo': [1, 2]},
...        {'bar': {'hello': 'world'}},
...        {'code': Code("function x() { return 1; }")},
...        {'bin': Binary("")}])
'[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$code": "function x() { return 1; }", "$scope": {}}}, {"bin": {"$binary": "AQIDBA==", "$type": "00"}}]'

Example usage (deserialization):

>>> from bson.json_util import loads
>>> loads('[{"foo": [1, 2]}, {"bar": {"hello": "world"}}, {"code": {"$scope": {}, "$code": "function x() { return 1; }"}}, {"bin": {"$type": "00", "$binary": "AQIDBA=="}}]')
[{u'foo': [1, 2]}, {u'bar': {u'hello': u'world'}}, {u'code': Code('function x() { return 1; }', {})}, {u'bin': Binary('...', 0)}]

Alternatively, you can manually pass the default to json.dumps(). It won’t handle Binary and Code instances (as they are extended strings you can’t provide custom defaults), but it will be faster as there is less recursion.

Changed in version 2.8: The output format for Timestamp has changed from ‘{“t”: <int>, “i”: <int>}’ to ‘{“$timestamp”: {“t”: <int>, “i”: <int>}}’. This new format will be decoded to an instance of Timestamp. The old format will continue to be decoded to a python dict as before. Encoding to the old format is no longer supported as it was never correct and loses type information. Added support for $numberLong and $undefined - new in MongoDB 2.6 - and parsing $date in ISO-8601 format.

Changed in version 2.7: Preserves order when rendering SON, Timestamp, Code, Binary, and DBRef instances.

Changed in version 2.3: Added dumps and loads helpers to automatically handle conversion to and from json and supports Binary and Code

bson.json_util.default(obj)
bson.json_util.dumps(obj, *args, **kwargs)

Helper function that wraps json.dumps.

Recursive function that handles all BSON types including Binary and Code.

Changed in version 2.7: Preserves order when rendering SON, Timestamp, Code, Binary, and DBRef instances.

bson.json_util.loads(s, *args, **kwargs)

Helper function that wraps json.loads.

Automatically passes the object_hook for BSON type conversion.

bson.json_util.object_hook(dct)

Previous topic

int64 – Tools for representing BSON int64

Next topic

max_key – Representation for the MongoDB internal MaxKey type

This Page