Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yamyamyuo/6bc86c9ea57d32f358a7913ad6aaf2cb to your computer and use it in GitHub Desktop.
Save yamyamyuo/6bc86c9ea57d32f358a7913ad6aaf2cb to your computer and use it in GitHub Desktop.
Create JSON dumps aware of datetime.datetime objects, in Python. #json #python #dumps #datetime
import json
import datetime
'''Create an encoder subclassing JSON.encoder.
Make this encoder aware of our classes (e.g. datetime.datetime objects)
'''
class Encoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.isoformat()
else:
return json.JSONEncoder.default(self, obj)
o = {
'a': {
'boo': 'far',
'created': datetime.now(),
},
'foo': 'Bar',
}
print json.dumps(o, cls=Encoder, indent=4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment