Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I have a basic dict as follows:

sample = {} sample['title'] = "String" sample['somedate'] = somedatetimehere

When I try to do jsonify(sample) I get:

TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable

What can I do such that my dictionary sample can overcome the error above?

Note: Though it may not be relevant, the dictionaries are generated from the retrieval of records out of MongoDB where when I print out str(sample['somedate']), the output is 2012-08-08 21:46:24.862000.

1 Answer

0 votes
by (106k points)

We have a simple solution based on a specific serializer that just converts datetime.datetime and datetime.date object to strings.

from datetime import date, datetime

def json_serial(obj):

     if isinstance(obj, (datetime, date)): 

           return obj.isoformat() 

    raise TypeError ("Type %s not serializable" % type(obj))

The above code just checks to find out if an object is of class datetime.datetime or datetime.date, and then uses .isoformat() to produce a serialized version of it. The code ends by raising an exception, to deal with the case it is called with a non-serializable type.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Dec 10, 2020 in Python by laddulakshana (16.4k points)
0 votes
2 answers
asked Jul 3, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jul 2, 2019 in Python by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...