PYTHON-4142 json_util.default should always convert Int64 (#1473)

This commit is contained in:
Shane Harvey 2024-01-12 10:57:54 -08:00 committed by GitHub
parent f67e9ae207
commit 72663deb33
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 16 additions and 1 deletions

View File

@ -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

View File

@ -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
------------------------

View File

@ -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