JSON (JavaScript Object Notation) lưu dữ liệu dạng dictionary. Python có thư viện json xử lý JSON.
Import json. Tạo hàm trả về JSON object: tạo dictionary, dùng json.dumps(dictionary) chuyển thành chuỗi JSON.
Cài JSON: pip install json (thường có sẵn trong Python).
Ví dụ
# Import JSON Library
import json
def fun():
title = "Python"
Tag = "Programming Language"
Category = "Open Source"
Downloads = "4500005230"
# Tạo dictionary
dictionary = {
"title": title,
"Tag": Tag,
"Category": Category,
"Downloads": Downloads
}
return json.dumps(dictionary)
print(fun())Kết quả
{"title": "Python", "Tag": "Programming Language", "Category": "Open Source", "Downloads": "4500005230"}