TypeError: Object of type ‘datetime‘ is not JSON serializable [Solved]

1. Problem description

When using python’s own json to convert data to json data, the data in datetime format reports an error: TypeError: Object of type’datetime’ is not JSON serializable

2. Solution

It is to rewrite and construct the json class, when encountering special date processing, the rest will be built-in.

from datetime import date, datetime

class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)

When using, json.dumps needs to call the class defined above, specify the cls parameter as ComplexEncoder, the code is as follows:

json.dumps(your_data, cls=ComplexEncoder)

3. Summary

As long as there is an error message about datetime xx is not JSON serializable at runtime, you can use the above methods to solve it perfectly.

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *