Cách parse JSON trong Python. Đầu tiên load file JSON dùng json.load(). Kết quả là Python dictionary. Sau đó truy cập trường bằng method của dictionary.
JSON là định dạng trao đổi dữ liệu nhẹ.
Để trích xuất thông tin từ file JSON hoặc response JSON, phải parse dữ liệu.
Parse JSON trong Python
Sử dụng JSON sau làm ví dụ:
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
Bước 1: Load file JSON trong Python:
import json
with open('store.json') as json_file:
data = json.load(json_file)
print(data)
File JSON giờ lưu trong biến data.
print(data) in ra JSON gốc.
Lưu ý: Phương pháp này lưu JSON dưới dạng Python dictionary. Kiểm tra bằng print(type(data)).
Trích xuất dữ liệu cụ thể từ JSON
Với JSON đã thành dictionary, lấy dữ liệu bằng key.
Ví dụ: lấy giá xe đạp (bicycle.price):
print(data['store']['bicycle']['price'])
Kết quả: 19.95
Trích xuất dữ liệu từ JSON Array
Trong JSON ví dụ, trường "book" là JSON Array.
Dùng index notation để lấy item cụ thể.
Ví dụ: lấy title của cuốn sách thứ 2 (index 1):
print(data['store']['book'][1]['title'])
Kết quả: Sword of Honour
Conditional Parsing of JSON (Parse có điều kiện)
Giả sử muốn lấy tất cả sách có giá ≤ 10.00:
books = data['store']['book']
for book in books:
if book['price'] <= 10.00:
print(book)
Kết quả:
{'category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 8.95}
Kết luận
Bài viết trình bày parse JSON trong Python. Point mấu chốt: load JSON file -> lưu thành Python dictionary -> dùng method dictionary bình thường để trích xuất giá trị cụ thể.