Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Định dạng JSON trong Python

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

PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
True, Falsetrue, false
Nonenull

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.