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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM