Python JSON
How do I fix "Object of type datetime is not JSON serializable" in Python?
This error occurs because Python datetime objects are not natively JSON-serializable. Fix it by providing a custom serializer to json.dumps() using the default parameter: json.dumps(data, default=str) converts datetime to string. For more control, create a custom handler: def handler(obj): if isinstance(obj, datetime): return obj.isoformat(); return str(obj). Then use: json.dumps(data, default=handler). Alternatively, convert datetime to strings before serialization or use libraries like simplejson that handle more types. The isoformat() method produces ISO 8601 strings that are widely recognized. After fixing serialization, use our JSON Formatter at jsonconsole.com/json-formatter to verify the output is properly formatted. For production code, consider using dataclasses with custom encoders or Pydantic models that handle serialization automatically. Always test your serialized JSON to ensure dates are formatted as expected.
Last updated: December 23, 2025
Previous
What is the difference between json.load() and json.loads()?
Next
How do you pretty-print JSON in Python with indentation?
Related Questions
What is the difference between json.load() and json.loads()?
Learn the difference between json.load() and json.loads() in Python. Understand when to use each method for parsing JSON.
How do you pretty-print JSON in Python with indentation?
Learn how to pretty-print JSON in Python with indentation. Master json.dumps() parameters for formatted output.
How can I convert a JSON string into a custom Python object?
Learn how to convert JSON strings to custom Python objects. Master object_hook, dataclasses, and Pydantic for JSON deserialization.
Still have questions?
Can't find the answer you're looking for? Please reach out to our support team.