Skip to content

Instantly share code, notes, and snippets.

@drmalex07
Created May 15, 2014 12:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save drmalex07/5149635e6ab807c8b21e to your computer and use it in GitHub Desktop.
Save drmalex07/5149635e6ab807c8b21e 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)
@kndo
Copy link

kndo commented Oct 25, 2018

Line 9 should be if isinstance(obj, datetime.datetime):

@xlyk
Copy link

xlyk commented Nov 8, 2018

thanks for this

@worldmind
Copy link

There are many modules for this task, maybe right way is select one.

@Eduard-gan
Copy link

Eduard-gan commented Jun 30, 2019

@worldmind Thanks for the info about these modules!

maybe right way is select one.

I hear this every time. People are way too smart, they're know the right way, they telling you that you sholdn't code anything that was once done and published by another smart person. Even if it is a 5 string long configuration-like solution.

The price is another dependency and it's dependencies to maintain in your project and since you're using foreign lib to solve simple problem you just loose any control over implementation of the solution and it's also it's not bug-free, you are just getting another set of bugs instead of those in your own solution.

@worldmind
Copy link

@Eduard-gan it's a big holywar ) IMHO we must make a new job, not repeat job that already done, of course I suppose that this job is good job.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment