ficapy
7/13/2015 - 5:23 AM

json序列化使用default参数简单忽略错误

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