How to fix "TypeError: Object of type datetime is not JSON serializable" in python ?

Created April 04, 2022 | Viewed 958 | by Benjamin Edit


Example of how to fix the TypeError: Object of type datetime is not JSON serializable" in python:

Let's consider an example:

Create a datetime object

Reminder: to create a datetime object in python

import datetime

x = datetime.datetime.now()

gives for example

2022-04-04 14:16:59.604425

which is a datetime object

Create a json file

Now if we try to create a json file using a dictionary with a datetime object inside:

import json

dict = {"member #002":{"first name": "John", "last name": "Doe", "age": 34, "Date":datetime.datetime.now()},
                "member #003":{"first name": "Elijah", "last name": "Baley", "age": 27, "Date":datetime.datetime.now()},
                "member #001":{"first name": "Jane", "last name": "Doe", "age": 42, "Date":datetime.datetime.now()}}

with open('data.json', 'w') as fp:
        json.dump(dict, fp,  indent=4)

it will returns the following error:

TypeError: Object of type datetime is not JSON serializable

To fix that a straightforward solution is to add the optin "default=str":

        json.dump(dict, fp,  indent=4, default=str)

References