Hướng dẫn save json file 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.

Python JSON
dict object
list, tuple array
str string
int, float number
True true
False false
None null
import json

data_dict = {
    "domainname": "gochocit.com",
    "active": True,
    "numberposts": 360,
    "category": ["hardware", "software", "network"],
    "facebookpage": "//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: 
type of data_string: 
{"domainname": "gochocit.com", "active": true, "numberposts": 360, "category": ["hardware", "software", "network"], "facebookpage": "//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": "//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": "//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": "//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": "//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": "//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": "//www.facebook.com/gochocit/",
    "numberposts": 360
}

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": "//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": "//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[].

  • Session là gì? Sử dụng session trong PHP
  • Cài đặt Python và môi trường lập trình với Visual Studio Code
  • Các kỹ thuật lập trình với mảng một chiều và minh họa với C++
  • Lớp Reader và Writer trong Java
  • Nạp chồng toán tử [operator overloading] trong Python

import json

data_dict = {
    "domainname": "gochocit.com",
    "active": True,
    "numberposts": 360,
    "category": ["hardware", "software", "network"],
    "facebookpage": "//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": "//www.facebook.com/gochocit/",
    "numberposts": 360
}

Chủ Đề