Created
October 15, 2013 23:53
-
-
Save simonw/7000493 to your computer and use it in GitHub Desktop.
How to use custom Python JSON serializers and deserializers to automatically roundtrip complex types.
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 json, datetime | |
class RoundTripEncoder(json.JSONEncoder): | |
DATE_FORMAT = "%Y-%m-%d" | |
TIME_FORMAT = "%H:%M:%S" | |
def default(self, obj): | |
if isinstance(obj, datetime.datetime): | |
return { | |
"_type": "datetime", | |
"value": obj.strftime("%s %s" % ( | |
self.DATE_FORMAT, self.TIME_FORMAT | |
)) | |
} | |
return super(RoundTripEncoder, self).default(obj) | |
data = { | |
"name": "Silent Bob", | |
"dt": datetime.datetime(2013, 11, 11, 10, 40, 32) | |
} | |
print json.dumps(data, cls=RoundTripEncoder, indent=2) | |
import json, datetime | |
from dateutil import parser | |
class RoundTripDecoder(json.JSONDecoder): | |
def __init__(self, *args, **kwargs): | |
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs) | |
def object_hook(self, obj): | |
if '_type' not in obj: | |
return obj | |
type = obj['_type'] | |
if type == 'datetime': | |
return parser.parse(obj['value']) | |
return obj | |
print json.loads(s, cls=RoundTripDecoder) | |
@Timokasse @simonw I think it is simpler than that, unless I am misunderstanding.
>>> import json
>>> import datetime
>>> data = {
... "name": "Silent Bob",
... "dt": datetime.datetime(2013, 11, 11, 10, 40, 32)
... }
# Fails as expected
>>> json.dumps(data)
TypeError: Object of type datetime is not JSON serializable
# Succeeds
>>> json.dumps(data, default=str)
'{"name": "Silent Bob", "dt": "2013-11-11 10:40:32"}'
@andelink Oh great type for the encoder part. However this encoder structure is future proof if you need other types to serialize that might not be serializable as string (but as record) like list of paragraph (that might contains comma).
@Timokasse @foresmac I did a version with the desired condensed shape.
https://gist.github.com/Et7f3/922260074697e585bb492b5f2e7e1166
@setaou does your scanner is equivalent to my trick with except ValueError
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@raph92 it acts recursively. This is my implementation.
INPUT
JSON
OUTPUT