zoukankan      html  css  js  c++  java
  • python之json扩展

    #!/usr/bin/env python
    # -*- coding: utf8 -*-
    # __Author: "Skiler Hao"
    # date: 2017/4/9 15:26
    import json
    from json.encoder import JSONEncoder
    
    
    class SkilerEncoder(JSONEncoder):
        """
        默认的json只支持以下内容的序列化,我们可以对原装json的JsonEncoder作进一步扩展
        +-------------------+---------------+
        | Python            | JSON          |
        +===================+===============+
        | dict              | object        |
        +-------------------+---------------+
        | list, tuple       | array         |
        +-------------------+---------------+
        | str               | string        |
        +-------------------+---------------+
        | int, float        | number        |
        +-------------------+---------------+
        | True              | true          |
        +-------------------+---------------+
        | False             | false         |
        +-------------------+---------------+
        | None              | null          |
        +-------------------+---------------+
            To extend this to recognize other objects, subclass and implement a
        ``.default()`` method with another method that returns a serializable
        object for ``o`` if possible, otherwise it should call the superclass
        implementation (to raise ``TypeError``).
        补充一下,o是啥?o就是我们平常使用的时候json.dumps(object),放入sumps的对象简称o
        翻译以下官方的哈:
        要扩展json识别更多的对象,需要创建JSONEncoder一个子类。实现default()方法
        default方法,可以对某样扩展的对象处理,返回可以序列化的对象
        要么继承父类的default()方法(内容为Type error 当前对象不可实例化)
    #     """
        def default(self, o):
            """
            来自官方文档的例子,实现对可迭代对象的序列化,我仅仅是搬运工,扩展还是交给大家吧
            For example, to support arbitrary iterators, you could
            implement default like this::
    
                def default(self, o):
                    try:
                    # 如果传递的是可以可以转化为可迭代的对象,那就转化
                        iterable = iter(o)
    
                    except TypeError:
                    # 如果转化失败,啥都不做,交给最好一行,父类处理(抛出类型异常)
                        pass
                    else:
                    # 否则就将其转化为list对象list对象是可以用默认json序列化的
                        return list(iterable)
                    # Let the base class default method raise the TypeError
                    # 调用父类的default方法
                    return JSONEncoder.default(self, o)
    
            """
    
            try:
                if isinstance(o, complex):
                    return str(o.real)+ '+' + str(o.imag) + 'j'
                # 例如复数是不能转化的,我们将其转化为字符串
                # 如果传递的是可以可以转化为可迭代的对象,那就转化
    
                # 如果对象是iterable我们可以将其转化为iter(o)转化为可迭代对象
                iterable = iter(o)
    
            except TypeError:
                # 如果转化失败,啥都不做,交给最好一行,父类处理(抛出类型异常)
                pass
            else:
                # 否则就将其转化为list对象list对象是可以用默认json序列化的
                return list(iterable)
            # Let the base class default method raise the TypeError
            # 调用父类的default方法
            return JSONEncoder.default(self, o)
    
    if __name__ == '__main__':
        a = [x for x in range(1,10)]
        b= 1 + 2j
    
        c = json.dumps(a,cls=SkilerEncoder)
        d = json.dumps(b,cls=SkilerEncoder)
        print(b)
  • 相关阅读:
    poj 1655 Balancing Act 树的重心
    poj 1985 Cow Marathon 树的直径
    hdu 4607 Park Visit 求树的直径
    hdu 1548 A strange lift 宽搜bfs+优先队列
    poj 2711 Leapin' Lizards && BZOJ 1066: [SCOI2007]蜥蜴 最大流
    poj 2449 Remmarguts' Date K短路+A*
    hdu 1285 确定比赛名次 拓扑排序
    hdu 3061 Battle 最大权闭合图
    hdu 3879 Base Station 最大权闭合图
    poj 2987 Firing 最大权闭合图
  • 原文地址:https://www.cnblogs.com/skiler/p/6831769.html
Copyright © 2011-2022 走看看