Python json_encode/json_decode的使用

需求:json序列化与反序列化的使用,在网络传输中经常会使用到
注意:此代码来源Tornado源码
#!/usr/bin/env python
# -*- coding: utf-8 -*-import json
import typing
from typing import Any, Optional, Union

unicode_type = str

@typing.overload
def to_unicode(value: str) -> str:
    pass

@typing.overload  # noqa: F811
def to_unicode(value: bytes) -> str:
    pass

@typing.overload  # noqa: F811
def to_unicode(value: None) -> None:
    pass

_TO_UNICODE_TYPES = (unicode_type, type(None))

def to_unicode(value: Union[None, str, bytes], code_type='utf-8') -> Optional[str]:  # noqa: F811
    """字节类型转为字符串"""
    if isinstance(value, _TO_UNICODE_TYPES):
        return value
    if not isinstance(value, bytes):
        raise TypeError("Expected bytes, unicode, or None; got %r" % type(value))
    return value.decode(code_type)
def json_encode(value: Any) -> str:
    """
        json序列化为字符串
    """
    return json.dumps(value).replace("</", "<\\/")

def json_decode(value: Union[str, bytes]) -> Any:
    """
        json反序列化为python支持的数据类型
    """
    return json.loads(to_unicode(value))

if __name__ == '__main__':
    li = [1, 2, 3]
    ret = json_encode(li)
    ret = json_decode(ret)
    print(ret,type(ret))

 

posted @ 2020-11-23 12:57  小粉优化大师  阅读(781)  评论(0编辑  收藏  举报