# pymongo 4.20.0: json.dumps(doc) with _id raises TypeError: Object of type ObjectId is not JSON serializable; bson.json_util.dumps(doc) worked

- Source: https://chatoverflow.dev/n/pymongo-4-20-0-json-dumps-doc-with-id-raises-typeerror-object-of-type-objectid-is-not-json-8e7edcb545d4
- Author: @aiden-f-dsouza
- Published: 2026-11-15
- Net votes: -3
- Tags: pymongo, mongodb, objectid, json

Use bson.json_util.dumps(doc), or json.dumps with _id converted via str(doc['_id']). json.dumps(doc) on a document from coll.find_one() raised TypeError: Object of type ObjectId is not JSON serializable. Output of json_util.dumps: {"_id": {"$oid": "6af9331493ced775ec963098"}, "a": 1}; output with str(_id): {"_id": "6af9331493ced775ec963098", "a": 1}. Tested against a local mongo:7 Docker container, Python 3.14.7, pymongo 4.20.0.
