Đọc (read) file JSON với Python

Đây là bài 44/54 bài của series môn học Ngôn ngữ lập trình Python

1. JSON (JavaScript Object Notation) là gì?

JSON (JavaScript Object Notation) là một định dạng (format) dữ liệu bắt nguồn từ ngôn ngữ Javascript. Dữ liệu trong JSON chủ yếu là text, được lưu trữ theo cặp thuộc tính (attribute) – giá trị (value). JSON thường được sử dụng trong các trường hợp:

  • Phát triển web: truyền gửi dữ liệu từ server đến client và ngược lại.
JSON sử dụng trong web application
  • Các file cấu hình (configuration files): JSON có thể được sử dụng để lưu trữ các cấu hình (configurations) và cài đặt (settings) trong các ứng dụng. Ví dụ như file settings.json trong Visual Studio Code.
File settings.json trong Visual Studio Code
  • Hoặc đơn giản là dùng JSON để lưu trữ dữ liệu.
Dùng JSON để lưu trữ dữ liệu

Bên dưới là ví dụ file info.json lưu trữ dữ liệu về thông tin của website gochocit.com.

info.json
{ 
    "domainname": "gochocit.com",
    "active": true,
    "numberposts": 360,
    "category": ["hardware", "software", "network"],
    "facebookpage": "https://www.facebook.com/gochocit/",
    "build": {
        "language": "php",
        "cms": "wordpress",
        "database": "mysql"
    }
}

Các lưu ý chính về định dạng của JSON là:

  • JSON bao gồm một chuỗi các cặp key – value (có thể gọi là attribute – value). Và chúng được bao quanh bởi dấu ngoặc nhọn {}.
  • Mỗi cặp key – value có định dạng "key": <value>. Value có thể là bất kỳ kiểu dữ liệu nào như object, list, string, number, boolean, null,
  • Các cặp key – value được cách nhau bởi dấu phẩy ,. Chỉ cặp key – value cuối cùng thì không có dấu phẩy , phía sau.

Lưu ý: Chúng ta nên sử dụng thụt đầu dòng (indentation) để làm cho JSON rõ ràng, dễ đọc hơn.

2. Đọc (read) file JSON với module json trong Python

Python xây dựng sẵn module json để làm việc với JSON. Chúng ta cần import json để sử dụng module này. Nhưng trước hết, chúng ta cần mở (open)đọc (read) file JSON để đọc dữ liệu JSON từ file với hàm json.load().

import json

with open('info.json', 'r') as f:
  data = json.load(f)

print(type(data))
print(data)
Kết quả
<class 'dict'>
{'domainname': 'gochocit.com', 'active': True, 'numberposts': 360, 'category': ['hardware', 'software', 'network'], 'facebookpage': 'https://www.facebook.com/gochocit/', 'build': {'language': 'php', 'cms': 'wordpress', 'database': 'mysql'}}

Hàm json.load() sẽ phân tích dữ liệu JSON và trả về một dictionary để xử lý được với Python. Lúc này, chúng ta có thể dễ dàng truy cập value của các cặp key – value trong dữ liệu JSON.

import json

with open('info.json', 'r') as f:
  data = json.load(f)

# access value of key-value
print(data["domainname"])
print(data["active"])
print(data["numberposts"])
print(data["category"])
print(data["facebookpage"])
print(data["build"])

category = data["category"]
build = data["build"]
print("type of category:", type(category))
print("type of build:", type(build))
Kết quả
gochocit.com
True
360
['hardware', 'software', 'network']
https://www.facebook.com/gochocit/
{'language': 'php', 'cms': 'wordpress', 'database': 'mysql'}
type of category: <class 'list'>
type of build: <class 'dict'>

Nếu các bạn đang có một JSON string thì cần sử dụng hàm json.loads() để convert sang dictionary trong Python.

import json

data_string = """
{
    "domainname": "gochocit.com",
    "active": true,
    "numberposts": 360,
    "category": ["hardware", "software", "network"],
    "facebookpage": "https://www.facebook.com/gochocit/",
    "build": {
        "language": "php",
        "cms": "wordpress",
        "database": "mysql"
    }
}
"""
#convert json string to dictionary
data = json.loads(data_string)

# access value of key-value
print(data["domainname"])
print(data["active"])
print(data["numberposts"])
print(data["category"])
print(data["facebookpage"])
print(data["build"])

category = data["category"]
build = data["build"]
print("type of category:", type(category))
print("type of build:", type(build))
Kết quả
gochocit.com
True
360 
['hardware', 'software', 'network']
https://www.facebook.com/gochocit/
{'language': 'php', 'cms': 'wordpress', 'database': 'mysql'}
type of category: <class 'list'>
type of build: <class 'dict'>

Khi chuyển đổi (convert) từ JSON string sang dictionary trong Python, chúng ta sẽ có data type của value trong JSON sẽ được chuyển đổi thành các data type tương ứng trong Python. Bảng bên dưới tóm tắt data type của value trong JSON sẽ được chuyển thành data type tương ứng trong Python.

JSONPython
objectdict
arraylist
stringstr
number (int)int
number (float)float
trueTrue
falseFalse
nullNone

Bảng chuyển đổi data type ở trên cũng được áp dụng tương tự khi chúng ta đọc dữ liệu từ JSON file.

5/5 - (3 bình chọn)
Bài trước và bài sau trong môn học<< Ghi (write) file XML với PythonGhi (write) file JSON với Python >>
Chia sẻ trên mạng xã hội:

Trả lời

Lưu ý:

1) Vui lòng bình luận bằng tiếng Việt có dấu.

2) Khuyến khích sử dụng tên thật và địa chỉ email chính xác.

3) Mọi bình luận trái quy định sẽ bị xóa bỏ.