diff --git a/bson/json_util.py b/bson/json_util.py index ada6e89c5..e6bc562d6 100644 --- a/bson/json_util.py +++ b/bson/json_util.py @@ -852,7 +852,7 @@ def _encode_int64(obj: Int64, json_options: JSONOptions) -> Any: if json_options.strict_number_long: return {"$numberLong": str(obj)} else: - return obj + return int(obj) # Encoders for BSON types diff --git a/doc/changelog.rst b/doc/changelog.rst index 98f535245..62bd6d851 100644 --- a/doc/changelog.rst +++ b/doc/changelog.rst @@ -14,6 +14,14 @@ PyMongo 4.7 brings a number of improvements including: - Replaced usage of :class:`bson.son.SON` on all internal classes and commands to dict, :attr:`options.pool_options.metadata` is now of type ``dict`` as opposed to :class:`bson.son.SON`. - Significantly improved the performance of encoding BSON documents to JSON. +- Fixed a bug where :class:`~bson.int64.Int64` instances could not always be encoded by `orjson`_. The following now + works:: + + >>> import orjson + >>> from bson import json_util + >>> orjson.dumps({'a': Int64(1)}, default=json_util.default, option=orjson.OPT_PASSTHROUGH_SUBCLASS) + +.. _orjson: https://github.com/ijl/orjson Changes in Version 4.6.1 ------------------------ diff --git a/test/test_json_util.py b/test/test_json_util.py index 003593f59..43007808c 100644 --- a/test/test_json_util.py +++ b/test/test_json_util.py @@ -545,6 +545,13 @@ class TestJsonUtil(unittest.TestCase): self.assertEqual(json_util.dumps({"weight": Int64(65535)}), '{"weight": 65535}') json_options = JSONOptions(strict_number_long=True, json_mode=JSONMode.LEGACY) self.assertEqual(json_util.dumps({"weight": Int64(65535)}, json_options=json_options), jsn) + # Ensure json_util.default converts Int64 to int in non-strict mode. + converted = json_util.default(Int64(65535)) + self.assertEqual(converted, 65535) + self.assertNotIsInstance(converted, Int64) + self.assertEqual( + json_util.default(Int64(65535), json_options=json_options), {"$numberLong": "65535"} + ) def test_loads_document_class(self): # document_class dict should always work