Ghi (write) file JSON với Python

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

Trước khi đọc bài này, các bạn nên đọc bài Đọc (read) file JSON với Python để biết khái niệm cơ bản của JSON cũng như cách đọc một file JSON. Với những kiến thức đó, các bạn sẽ dễ dàng hiểu được những cách ghi (write) file JSON trong Python.

1. Chuyển đổi (convert) dictionary sang JSON trong Python

Chúng ta có thể chuyển đổi (convert) dictionary thành JSON string bằng cách sử dụng hàm json.dumps() trong module json. Khi chuyển đổi (convert) từ dictionary trong Python thành JSON string, chúng ta sẽ có các object trong Python sẽ được chuyển đổi thành các data type tương ứng trong JSON. Bảng bên dưới tóm tắt các loại object trong Python sẽ được chuuyển thành data type tương ứng trong JSON.

PythonJSON
dictobject
list, tuplearray
strstring
int, floatnumber
Truetrue
Falsefalse
Nonenull
import json

data_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"
    }
}
print("type of data_dict:", type(data_dict))

#convert dictionary to json string
data_string = json.dumps(data_dict)

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

1.1. In (print) JSON string với thụt đầu dòng (Indentation)

Trong ví dụ ở phần trên, JSON string được in ra không có thụt đầu dòng, rất khó nhìn. Chúng ta có thể in (print) JSON string với thụt đầu dòng (Indentation) với bằng cách truyền giá trị cho tham số indent của hàm json.dumps().

import json

data_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"
    }
}

#convert dictionary to json string with indentation
data_string = json.dumps(data_dict, indent=4)
print(data_string)
Kết quả
{
    "domainname": "gochocit.com",
    "active": true,
    "numberposts": 360,
    "category": [
        "hardware",
        "software",
        "network"
    ],
    "facebookpage": "https://www.facebook.com/gochocit/",
    "build": {
        "language": "php",
        "cms": "wordpress",
        "database": "mysql"
    }
}

1.2. Sắp xếp (sort) JSON string với key trong JSON

Chúng ta có thể sắp xếp key trong JSON theo thứ tự của bảng chữ cái khi in (print) ra. Để làm việc này, chúng ta truyền giá trị True cho tham số sort_keys của hàm json.dumps().

import json

data_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"
    }
}

#convert dictionary to json string with sort_keys
data_string = json.dumps(data_dict, sort_keys=True)
print(data_string)
Kết quả
{"active": true, "build": {"cms": "wordpress", "database": "mysql", "language": "php"}, "category": ["hardware", "software", "network"], "domainname": "gochocit.com", "facebookpage": "https://www.facebook.com/gochocit/", "numberposts": 360}

1.3. JSON string với sort và indentation trong Python

Khi muốn tạo ra JSON string với sort và indentation, chúng ta truyền giá trị cho cả 2 tham số trên.

import json

data_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"
    }
}

#convert dictionary to json string with sort_keys and indent
data_string = json.dumps(data_dict, sort_keys=True, indent=4)
print(data_string)
Kết quả
{
    "active": true,
    "build": {
        "cms": "wordpress",
        "database": "mysql",
        "language": "php"
    },
    "category": [
        "hardware",
        "software",
        "network"
    ],
    "domainname": "gochocit.com",
    "facebookpage": "https://www.facebook.com/gochocit/",
    "numberposts": 360
}

2. Ghi (write) file JSON trong Python

Khi đã tạo ra được JSON string thì việc ghi dữ liệu JSON vào file là hết sức dễ dàng. Việc này giống như việc ghi (write) một file trong Python.

import json

data_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"
    }
}

#convert dictionary to json string with sort_keys and indent
data_string = json.dumps(data_dict, sort_keys=True, indent=4)

# write json string to file
myjsonfile = open("info2.json", "w")
myjsonfile.write(data_string)
myjsonfile.close()
Kết quả nội dung của file info2.json được tạo ra
{
    "active": true,
    "build": {
        "cms": "wordpress",
        "database": "mysql",
        "language": "php"
    },
    "category": [
        "hardware",
        "software",
        "network"
    ],
    "domainname": "gochocit.com",
    "facebookpage": "https://www.facebook.com/gochocit/",
    "numberposts": 360
}

Nếu chúng ta muốn tạo ra JSON string từ một object trong Python rồi ghi JSON string vào file chỉ với 2 câu lệnh thì có thể sử dụng hàm json.dump().

import json

data_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"
    }
}

# write json string to file
with open("info2.json", 'w') as file:
    json.dump(data_dict, file, sort_keys=True, indent=4)
file.close()
Kết quả nội dung của file info2.json được tạo ra
{
    "active": true,
    "build": {
        "cms": "wordpress",
        "database": "mysql",
        "language": "php"
    },
    "category": [
        "hardware",
        "software",
        "network"
    ],
    "domainname": "gochocit.com",
    "facebookpage": "https://www.facebook.com/gochocit/",
    "numberposts": 360
}
5/5 - (1 bình chọn)
Bài trước và bài sau trong môn học<< Đọc (read) file JSON với PythonChuyển đổi (convert) dữ liệu XML sang dữ liệu JSON trong 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ỏ.