fix custom json encoder

This commit is contained in:
Alan Hamlett 2016-09-01 00:41:21 +02:00
parent dbec1d03a6
commit c08288eefd

View file

@ -13,7 +13,7 @@ import logging
import os import os
import traceback import traceback
from .compat import basestring, u from .compat import u
from .packages.requests.packages import urllib3 from .packages.requests.packages import urllib3
try: try:
from collections import OrderedDict # pragma: nocover from collections import OrderedDict # pragma: nocover
@ -27,16 +27,19 @@ except (ImportError, SyntaxError): # pragma: nocover
class CustomEncoder(json.JSONEncoder): class CustomEncoder(json.JSONEncoder):
def encode(self, obj):
try:
return super(CustomEncoder, self).encode(obj)
except UnicodeDecodeError:
obj = u(obj)
return super(CustomEncoder, self).encode(obj)
def default(self, obj): def default(self, obj):
if isinstance(obj, basestring): try:
return super(CustomEncoder, self).default(obj)
except TypeError:
obj = u(obj) obj = u(obj)
return json.dumps(obj) return super(CustomEncoder, self).default(obj)
try: # pragma: nocover
encoded = super(CustomEncoder, self).default(obj)
except UnicodeDecodeError: # pragma: nocover
obj = u(obj)
encoded = super(CustomEncoder, self).default(obj)
return encoded
class JsonFormatter(logging.Formatter): class JsonFormatter(logging.Formatter):