• Python 类对象的JSON序列化与反序列化


    1. Python 类对象

    class Token:
      def __init__(self, name, address, symbol, decimals):
        self.name = name
        self.address = address
        self.symbol = symbol
        self.decimals = decimals
    

    2. JSON 序列化Token对象

    import json
    
    token = Token('Tether USD', '0xdac17f958d2ee523a2206206994597c13d831ec7', 'USDT', 6)
    json.dumps(token)
    # TypeError: Object of type Token is not JSON serializable
    

    3. JSON.dumps 定义

    dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
        Serialize ``obj`` to a JSON formatted ``str``.
    ...
    ``default(obj)`` is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError.
    # 可参数default用于把任意一个对象变成一个可序列为JSON的对象
    ....
    

    4. JSON 序列化类对象

    json.dumps(u, default=lambda obj: obj.__dict__, sort_keys=True)
    # output:
    # '{"address": "0xdAC17F958D2ee523a2206206994597C13D831ec7", "decimals": 6, "name": "Tether USD", "symbol": "USDT"}'
    

    5. JSON.loads定义

    loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
        Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance containing a JSON document) to a Python object
    ``object_hook`` is an optional function that will be called with the result of any object literal decode (a ``dict``). The return value of
        ``object_hook`` will be used instead of the ``dict``. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).
    ...
    

    6. JSON反序列为类对象

    def handle(t):
      return Token(t['name'], t['address'], t['symbol'], t['decimals'])
    
    json_str = '{"address": "0xdAC17F958D2ee523a2206206994597C13D831ec7", "decimals": 6, "name": "Tether USD", "symbol": "USDT"}'
    token = json.loads(json_str, object_hook=handle)
    

    7. 参考

  • 相关阅读:
    poj 3264 Balanced Lineup
    poj 2762 Going from u to v or from v to u?
    hdu 3671 Boonie and Clyde
    zoj 3195 Design the city
    poj 1523 SPF
    Codeforces Polo the Penguin and Matrix
    MVC原理的简述(转)
    C#访问权限修饰符
    XML Schema介绍
    Sql批量删除/插入
  • 原文地址:https://www.cnblogs.com/yueyun00/p/14991745.html
Copyright © 2020-2023  润新知