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

Cách trả về JSON object từ hàm Python

Sử dụng json.dumps() để chuyển dict Python thành chuỗi JSON.

Ví dụ

import json

data = {'name': 'Sarah', 'age': 24, 'isEmployed': True}

def retjson():
    python2json = json.dumps(data)
    print(python2json)

retjson()

Đầu ra

{"age": 24, "isEmployed": true, "name": "Sarah"}

Các tham số hữu ích của json.dumps()

json.dumps(data, indent=2, ensure_ascii=False, sort_keys=True)
# indent=2: pretty print
# ensure_ascii=False: giữ unicode (tiếng Việt)
# sort_keys=True: sắp xếp key theo alphabet

Trả về dict (không phải string) cho API

Nếu dùng framework (Flask, FastAPI...), hãy trả về dict trực tiếp, framework sẽ tự serialize thành JSON response.