json_util
– Tools for using Python’s json module with BSON documents
This module provides two helper methods dumps and loads that wrap the native methods and provide explicit BSON conversion to and from JSON. JSONOptions provides a way to control how JSON is emitted and parsed, with the default being the legacy PyMongo format. can also generate Canonical or Relaxed Extended JSON when or RELAXED_JSON_OPTIONS is provided, respectively.
Example usage (deserialization):
Example usage (serialization):
Example usage (with ):
Example usage (with RELAXED_JSON_OPTIONS):
Alternatively, you can manually pass the default to . It won’t handle Binary and instances (as they are extended strings you can’t provide custom defaults), but it will be faster as there is less recursion.
Note
If your application does not need the flexibility offered by JSONOptions and spends a large amount of time in the json_util module, look to for a nice performance improvement. python-bsonjs is a fast BSON to MongoDB Extended JSON converter for Python built on top of libbson. python-bsonjs works best with PyMongo when using .
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 . 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
class bson.json_util.DatetimeRepresentation
LEGACY
= 0Legacy MongoDB Extended JSON datetime representation.
datetime.datetime instances will be encoded to JSON in the format {“$date”: <dateAsMilliseconds>}, where dateAsMilliseconds is a 64-bit signed integer giving the number of milliseconds since the Unix epoch UTC. This was the default encoding before PyMongo version 3.4.
New in version 3.4.
NUMBERLONG
= 1NumberLong datetime representation.
instances will be encoded to JSON in the format {“$date”: {“$numberLong”: “<dateAsMilliseconds>”}}, where dateAsMilliseconds is the string representation of a 64-bit signed integer giving the number of milliseconds since the Unix epoch UTC.
New in version 3.4.
ISO8601
= 2ISO-8601 datetime representation.
datetime.datetime instances greater than or equal to the Unix epoch UTC will be encoded to JSON in the format {“$date”: “<ISO-8601>”}. instances before the Unix epoch UTC will be encoded as if the datetime representation is NUMBERLONG.
New in version 3.4.
class bson.json_util.JSONMode
LEGACY
= 0Legacy Extended JSON representation.
In this mode, produces PyMongo’s legacy non-standard JSON output. Consider using RELAXED or instead.
RELAXED
= 1Relaxed Extended JSON representation.
In this mode, dumps() produces Relaxed Extended JSON, a mostly JSON-like format. Consider using this for things like a web API, where one is sending a document (or a projection of a document) that only uses ordinary JSON type primitives. In particular, the
int
, , andfloat
numeric types are represented in the native JSON number format. This output is also the most human readable and is useful for debugging and documentation.See also
The specification for Relaxed Extended JSON.
New in version 3.5.
class bson.json_util.JSONOptions
Encapsulates JSON options for and loads().
See also
The specification for Relaxed and Canonical .
New in version 3.4.
Changed in version 3.5: Accepts the optional parameter json_mode.
with_options
(\*kwargs*)Make a copy of this JSONOptions, overriding some options:
New in version 3.12.
bson.json_util.LEGACY_JSON_OPTIONS
= JSONOptions(strict_number_long=False, datetime_representation=0, strict_uuid=False, json_mode=0, document_class=dict, tz_aware=True, uuid_representation=UuidRepresentation.PYTHON_LEGACY, unicode_decode_error_handler=’strict’, tzinfo=<bson.tz_util.FixedOffset object>, type_registry=TypeRegistry(type_codecs=[], fallback_encoder=None))
JSONOptions for encoding to PyMongo’s legacy JSON format.
See also
The documentation for .
New in version 3.5.
= JSONOptions(strict_number_long=False, datetime_representation=0, strict_uuid=False, json_mode=0, document_class=dict, tz_aware=True, uuid_representation=UuidRepresentation.PYTHON_LEGACY, unicode_decode_error_handler=’strict’, tzinfo=<bson.tz_util.FixedOffset object>, type_registry=TypeRegistry(type_codecs=[], fallback_encoder=None))
The default JSONOptions for JSON encoding/decoding.
New in version 3.4.
bson.json_util.CANONICAL_JSON_OPTIONS
= JSONOptions(strict_number_long=True, datetime_representation=1, strict_uuid=True, json_mode=2, document_class=dict, tz_aware=True, uuid_representation=UuidRepresentation.PYTHON_LEGACY, unicode_decode_error_handler=’strict’, tzinfo=<bson.tz_util.FixedOffset object>, type_registry=TypeRegistry(type_codecs=[], fallback_encoder=None))
for Canonical Extended JSON.
See also
The documentation for bson.json_util.JSONMode.CANONICAL.
New in version 3.5.
bson.json_util.RELAXED_JSON_OPTIONS
= JSONOptions(strict_number_long=False, datetime_representation=2, strict_uuid=True, json_mode=1, document_class=dict, tz_aware=True, uuid_representation=UuidRepresentation.PYTHON_LEGACY, unicode_decode_error_handler=’strict’, tzinfo=<bson.tz_util.FixedOffset object>, type_registry=TypeRegistry(type_codecs=[], fallback_encoder=None))
for Relaxed Extended JSON.
See also
The documentation for bson.json_util.JSONMode.RELAXED.
New in version 3.5.
bson.json_util.STRICT_JSON_OPTIONS
= JSONOptions(strict_number_long=True, datetime_representation=2, strict_uuid=True, json_mode=0, document_class=dict, tz_aware=True, uuid_representation=UuidRepresentation.PYTHON_LEGACY, unicode_decode_error_handler=’strict’, tzinfo=<bson.tz_util.FixedOffset object>, type_registry=TypeRegistry(type_codecs=[], fallback_encoder=None))
DEPRECATED - for MongoDB Extended JSON’s Strict mode encoding.
New in version 3.4.
Changed in version 3.5: Deprecated. Use RELAXED_JSON_OPTIONS or instead.
bson.json_util.dumps
(obj, \args, **kwargs*)
Helper function that wraps json.dumps().
Recursive function that handles all BSON types including and Code.
Changed in version 3.4: Accepts optional parameter json_options. See .
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.
Raises TypeError
, ValueError
, KeyError
, or on invalid MongoDB Extended JSON.
Changed in version 3.5: Parses Relaxed and Canonical Extended JSON as well as PyMongo’s legacy format. Now raises TypeError
or ValueError
when parsing JSON type wrappers with values of the wrong type or any extra keys.
Changed in version 3.4: Accepts optional parameter json_options. See JSONOptions.
bson.json_util.object_pairs_hook
(pairs, json_options=JSONOptions(strict_number_long=False, datetime_representation=0, strict_uuid=False, json_mode=0, document_class=dict, tz_aware=True, uuid_representation=UuidRepresentation.PYTHON_LEGACY, unicode_decode_error_handler=’strict’, tzinfo=<bson.tz_util.FixedOffset object>, type_registry=TypeRegistry(type_codecs=[], fallback_encoder=None)))
bson.json_util.object_hook
(dct, json_options=JSONOptions(strict_number_long=False, datetime_representation=0, strict_uuid=False, json_mode=0, document_class=dict, tz_aware=True, uuid_representation=UuidRepresentation.PYTHON_LEGACY, unicode_decode_error_handler=’strict’, tzinfo=<bson.tz_util.FixedOffset object>, type_registry=TypeRegistry(type_codecs=[], fallback_encoder=None)))