Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
json序列化使用default参数简单忽略错误
import json
from bson import ObjectId
a = {'1': ObjectId('53ef2d847f55f618ce13f24')}
def default(o):
"""Implement this method in a subclass such that it returns
a serializable object for ``o``, or calls the base implementation
(to raise a ``TypeError``).
For example, to support arbitrary iterators, you could
implement default like this::
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
# Let the base class default method raise the TypeError
return JSONEncoder.default(self, o)
"""
# raise TypeError(repr(o) + " is not JSON serializable")
try:
iterable = iter(o)
except TypeError:
return repr(o)
else:
return list(iterable)
print(json.dumps(a, indent=4)) # 报错
print(json.dumps(a, indent=4, default=default))
print(json.dumps(a, indent=4, default=lambda x: repr(x)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.