← Back to Python, page 2

python-0035 · Easy fresher

Convert between JSON text and Python objects, and handle types JSON does not support.

json.dumps turns dicts, lists, strings, numbers, booleans and None into JSON text, and json.loads parses it back. Types like datetime, Decimal and sets are not supported directly; pass default=... to convert them, or convert before dumping. Tuples become lists and dict keys become strings.

Full answer
python
import json
from datetime import date
from decimal import Decimal
order = {"id": 7, "items": ("pen", "ink"), "paid": True, "note": None, 1: "x"}
text = json.dumps(order)
print(text)
print(json.loads(text))
data = {"day": date(2026, 12, 4), "amount": Decimal("45.50")}
try:
    json.dumps(data)
except TypeError as e:
    print("TypeError:", e)
print(json.dumps(data, default=str))
print(json.dumps({"name": "Asha", "city": "पुणे"}, ensure_ascii=False))

Output:

text
{"id": 7, "items": ["pen", "ink"], "paid": true, "note": null, "1": "x"}
{'id': 7, 'items': ['pen', 'ink'], 'paid': True, 'note': None, '1': 'x'}
TypeError: Object of type date is not JSON serializable
{"day": "2026-12-04", "amount": "45.50"}
{"name": "Asha", "city": "पुणे"}

The tuple came back as a list, None became null and back, and the integer key 1 became the string '1', so a round trip does not always return the same object. default=str converts unsupported values to text, which suits dates and Decimals in logs; for APIs, prefer explicit formats such as ISO dates. ensure_ascii=False keeps non-ASCII text readable instead of \u escapes.

python
import json
from datetime import date
from decimal import Decimal
order = {"id": 7, "items": ("pen", "ink"), "paid": True, "note": None, 1: "x"}
text = json.dumps(order)
print(text)
print(json.loads(text))
data = {"day": date(2026, 12, 4), "amount": Decimal("45.50")}
try:
    json.dumps(data)
except TypeError as e:
    print("TypeError:", e)
print(json.dumps(data, default=str))
print(json.dumps({"name": "Asha", "city": "पुणे"}, ensure_ascii=False))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • dumps and loads convert both ways
  • Tuples become lists; keys become strings
  • default handles unsupported types
  • ensure_ascii=False keeps Unicode readable

Common mistakes

  • Expecting exact round trips
  • Sending Decimal or datetime without converting

Follow-ups

  • How would you parse ISO dates back into datetime?
  • When would you use Pydantic for JSON?

Tips

  • Show what changes in a round trip