brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's json.dumps(default=str) stops the not serializable error

Python
~/tips/tip-python-json-dumps-default-str

import json

Write dates, decimals and paths to a file without a custom encoder class.

The moment a dict contains a datetime, json.dumps gives up with Object of type datetime is not JSON serializable. For quick output I’d pass one extra argument.

import json
from datetime import datetime
from decimal import Decimal

record = {"at": datetime(2026, 11, 30, 14, 5), "price": Decimal("1.10")}
print(json.dumps(record, default=str))
# {"at": "2026-11-30 14:05:00", "price": "1.10"}

default is a function that json calls for every object it doesn’t know how to handle. With str it turns datetimes, Decimals, Path objects and UUIDs into their text form, and everything json already understands stays as it was.

I’d use it for logging, debug dumps and small state files where you mostly want to see the data and don’t plan to read it back as the same types.

That’s also the limit. Everything comes back as a plain string when you load the file again, so a datetime is just text and a Decimal is no longer a number. And str on a datetime gives a space between date and time instead of the ISO T. If another program reads the file, write a small function that returns obj.isoformat() for datetimes and raises TypeError for anything you didn’t expect, so a surprise object doesn’t slip through as text.

Further reading: json.dumps

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link