Module json (stdlib) chuyển đổi giữa object Python và chuỗi JSON (serialize/deserialize).
1. Python → JSON String
import json
from io import StringIO
# dump: ghi vào file-like object
buf = StringIO()
json.dump(["India", "Australia", "Brazil"], buf)
print(buf.getvalue()) # ["India", "Australia", "Brazil"]
# dumps: trả về string
data = {"name": "Kalyan", "age": 25, "city": "Delhi"}
print(json.dumps(data, indent=4))
# {
# "name": "Kalyan",
# "age": 25,
# "city": "Delhi"
# }
2. JSON String → Python
# load: đọc từ file-like
buf = StringIO('["xyz", "abc", "pqr"]')
print(json.load(buf)) # ['xyz', 'abc', 'pqr']
# loads: parse từ string
s = '{"xyz": 1, "abc": 2, "pqr": 4}'
print(json.loads(s)) # {'xyz': 1, 'abc': 2, 'pqr': 4}
# Lưu ý: key trùng lặp ("xyz" xuất hiện 2 lần) → giữ giá trị cuối
3. JSONEncoder tùy chỉnh (complex number)
class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, complex):
return [obj.real, obj.imag]
return super().default(obj)
print(json.dumps(5+8j, cls=ComplexEncoder)) # [5.0, 8.0]
4. JSONDecoder tùy chỉnh
s = '{"Asim": 25, "Priyesh": 23, "Asim": "28"}'
print(json.JSONDecoder().decode(s)) # {'Asim': '28', 'Priyesh': 23}
print(json.JSONDecoder().raw_decode(s)) # (obj, end_index)
Bảng mapping Python ↔ JSON
| Python | JSON |
|---|---|
| dict | object |
| list, tuple | array |
| str | string |
| int, float | number |
| True, False | true, false |
| None | null |
Lưu ý
- JSON không hỗ trợ tuple, set, custom class → cần encoder tùy chỉnh.
ensure_ascii=Falseđể giữ Unicode (tiếng Việt).sort_keys=Trueđể sắp xếp key alphabet.