Created
July 13, 2015 05:23
-
-
Save ficapy/276cf86ee33566ddae31 to your computer and use it in GitHub Desktop.
json序列化使用default参数简单忽略错误
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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