-
Type: Task
-
Resolution: Unresolved
-
Priority: Minor - P4
-
None
-
Affects Version/s: None
-
Component/s: None
-
None
As requested in PYTHON-3395, we should update the ObjectId and other BSON types to link to docs for Extended JSON.
The hope is to make it easier for users to discover the bson.json_util module and how to use it to encode/decode BSON documents. For example to workaround this issue:
>>> import json >>> json.dumps({'_id': ObjectId()}) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type ObjectId is not JSON serializable
Use json_util.dumps instead:
>>> from bson import json_util >>> json_util.dumps({'_id': ObjectId()}) '{"_id": {"$oid": "62f568ce8a2abf3c4b1715c5"}}' >>> json_util.loads(_) {'_id': ObjectId('62f568ce8a2abf3c4b1715c5')}
- related to
-
PYTHON-3395 Make ObjectId properly convert when being served from a rest API
- Closed