Skip to content

Instantly share code, notes, and snippets.

@lvsmart
Created September 1, 2016 05:40
Show Gist options
  • Select an option

  • Save lvsmart/20252cb7fce742787beebf468086bf12 to your computer and use it in GitHub Desktop.

Select an option

Save lvsmart/20252cb7fce742787beebf468086bf12 to your computer and use it in GitHub Desktop.
JSONEncoder
import json
from datetime import datetime
from uuid import UUID
class LogJSONEncoder(json.JSONEncoder):
"""
专门为了解决各种:``TypeError: xx is not JSON serializable``
"""
def __new__(cls, *args, **kwargs):
"""
单例模式
"""
_instance = None
if not hasattr(cls, '_instance'):
cls._instance = super(LogJSONEncoder, cls).__new__(
cls, *args, **kwargs)
return cls._instance
def default(self, o):
"""
重写了默认的decode,主要针对三种类型:``bytes``, ``UUID``, ``datetime``
"""
if isinstance(o, bytes):
return decode_byte(o)
if isinstance(o, UUID):
return str(o)
if isinstance(o, datetime):
return o.isoformat()
return json.JSONEncoder.default(self, o)
def decode_byte(byte_string):
"""
request与response中的许多字段,都是 ``bytes``,需要decode
:param byte_string: b''
:return: str
"""
if isinstance(byte_string, bytes):
return byte_string.decode('utf-8')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment