Created
October 23, 2020 23:20
-
-
Save mzpqnxow/0fdcb2b6f6b8a73e8e7451af93c6e912 to your computer and use it in GitHub Desktop.
JSON encoder for standard Python json package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import codecs | |
import json | |
import datetime | |
from uuid import UUID | |
class UniversalEncoder(json.JSONEncoder): | |
def default(self, obj): | |
if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)): | |
return obj.isoformat() | |
if isinstance(obj, datetime.timedelta): | |
return (datetime.datetime.min + obj).time().isoformat() | |
if isinstance(obj, datetime.date): | |
return obj.strftime('%Y%m%d') | |
if isinstance(obj, datetime.time): | |
return obj.isoformat() | |
if isinstance(obj, datetime.timedelta): | |
return '{} days, {} seconds, {} microseconds'.format(obj.days, obj.seconds, obj.microseconds) | |
if isinstance(obj, float): | |
return str(obj) | |
if isinstance(obj, (set, tuple)): | |
return list(obj) | |
if isinstance(obj, UUID): | |
return obj.hex | |
if isinstance(obj, bytes): | |
for encoding in ('utf-8', 'ISO8859-1'): | |
try: | |
print('try {}'.format(encoding)) | |
return obj.decode(encoding) | |
except UnicodeDecodeError: | |
continue | |
# In JSON, this will come out as "\\xaa\\xbb" | |
return ''.join([r'\x{:x}'.format(obj[i]) for i in range(0, len(obj))]) | |
return super().default(obj) | |
from json import dumps | |
x = {} | |
print(dumps(x, cls=UniversalEncoder)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment