all Python 3Files & I/Oterm
json
json
JSON serialization and deserialization. dumps/loads work with strings, dump/load with files. Supports dict, list, str, int, float, bool and None.
Syntax
import json
json.dumps(obj)
json.loads(s)
A round trip is not an identity: a tuple comes back as a list, and non-string dict keys come back as strings, so 1 turns into '1'. ensure_ascii is True by default, which escapes anything non-Latin into \uXXXX — pass ensure_ascii=False when you want a human-readable file. Sets, datetime and Decimal are unsupported and raise TypeError; convert them yourself or hook the default parameter.
Examples
import json, os, tempfile
data = {'name': 'Alice', 'age': 30, 'langs': ['Python', 'Rust']}
print(json.dumps(data)) # → {"name": "Alice", "age": 30, "langs": ["Python", "Rust"]}
print(json.dumps(data, indent=2)) # красивый JSON с отступами
parsed = json.loads('{"x": 1, "y": [1, 2, 3]}')
print(parsed, type(parsed)) # → {'x': 1, 'y': [1, 2, 3]} <class 'dict'>
path = os.path.join(tempfile.gettempdir(), 'data.json')
with open(path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
with open(path, encoding='utf-8') as f:
loaded = json.load(f)
print(loaded['name']) # → Alice
import json, os, tempfile
# ensure_ascii=False — для кириллицы
d2 = {'имя':'Алиса'}
print(json.dumps(d2, ensure_ascii=False)) # → {"имя": "Алиса"}
import json, os, tempfile
# JSONDecodeError
try:
json.loads('invalid')
except json.JSONDecodeError as e:
print(e) # → Expecting value...
import json, os, tempfile
# Кастомный default для нестандартных типов
from datetime import date
def default(obj):
if isinstance(obj, date):
return obj.isoformat()
raise TypeError
print(json.dumps({'date': date(2024,1,1)}, default=default)) # → {"date":"2024-01-01"}
import json, os, tempfile
# sort_keys
print(json.dumps({'b':2,'a':1}, sort_keys=True)) # → {"a": 1, "b": 2}
See also
Open in the full glossarydocs.python.orgReport an inaccuracy