需求: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))