Chuyển đổi (convert) dữ liệu XML sang dữ liệu JSON trong Python

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

XMLJSON là 2 định dạng (format) dữ liệu được sử dụng phổ biến nhất hiện nay. Trong Python, chúng ta có thể chuyển đổi (convert) giữa 2 định dạng dữ liệu này. Bài này sẽ sử dụng module xmltodict để convert XML sang JSON trong Python.

Trước khi đọc bài này, các bạn nên đọc các bài về XML và JSON trong Python sau:

1. Cài đặt module xmltodict trong Python

Module xmltodict được sử dụng để chuyển đổi (convert) định dạng dữ liệu XML sang định dạng dữ liệu JSON trong Python. Module này không có sẵn trong Python. Để sử dụng được module xmltodict, chúng ta cần cài đặt module này với câu lệnh sau:

pip install xmltodict

Để tìm hiểu kỹ hơn về thư viện này, các bạn có thể truy cập vào website của project xmltodict 0.12.0.

Các bạn có thể đọc lại bài Cài đặt Python và môi trường lập trình với Visual Studio Code để biết cách cài đặt các thư viện Python trong Visual Studio Code.

2. Chuyển đổi (convert) dữ liệu XML sang dữ liệu JSON trong Python

Chúng ta có một số bước để convert XML sang JSON trong Python:

Bước 1. Mở (open) và đọc (read) dữ liệu trong file XML để được XML string.

Bước 2. Chuyển đổi (convert) XML string thành dictionary trong Python với hàm xmltodict.parse().

Bước 3. Chuyển dictionary thành JSON string trong Python.

Giả sử, chúng ta có file info.xml với nội dung như bên dưới.

<website>
    <domainname>gochocit.com</domainname>
    <active>True</active>
    <numberposts>360</numberposts>
    <category>
        <item>hardware</item>
        <item>software</item>
        <item>network</item>
    </category>
    <facebookpage>https://www.facebook.com/gochocit/</facebookpage>
    <build>
        <language>php</language>
        <cms>wordpress</cms>
        <database>mysql</database>
    </build>
</website>

File info.xml ở trên chỉ gồm các thẻ (tag) mà không có thuộc tính. Đoạn code bên dưới giúp chuyển đổi dữ liệu XML trong file info.xml thành JSON.

import xmltodict, json

# read file xml
with open("info.xml") as file:
    data_xml = file.read()
# convert xml string to dictionary
data_dict = xmltodict.parse(data_xml)
# convert dictionary to json string
data_json = json.dumps(data_dict, indent=4)
# print xml string, dictionary, json string
print("type of data_xml:", type(data_xml))
print("type of data_dict:", type(data_dict))
print("type of data_json:", type(data_json))
print(data_json)
Kết quả
type of data_xml: <class 'str'>
type of data_dict: <class 'collections.OrderedDict'>
type of data_json: <class 'str'>
{
    "website": {
        "domainname": "gochocit.com",
        "active": "True",
        "numberposts": "360",
        "category": {
            "item": [
                "hardware",
                "software",
                "network"
            ]
        },
        "facebookpage": "https://www.facebook.com/gochocit/",
        "build": {
            "language": "php",
            "cms": "wordpress",
            "database": "mysql"
        }
    }
}

Có thể thấy, các tag trong XML sẽ được chuyển thành key, các text của tag sẽ được chuyển thành value trong JSON.

Giả sử, file info1.xml có gồm các thẻ (tag) và thuộc tính post của tag item như bên dưới.

<website>
    <domainname>gochocit.com</domainname>
    <active>True</active>
    <numberposts>360</numberposts>
    <category>
        <item post="50">hardware</item>
        <item post="150">software</item>
        <item post="17">network</item>
    </category>
    <facebookpage>https://www.facebook.com/gochocit/</facebookpage>
    <build>
        <language>php</language>
        <cms>wordpress</cms>
        <database>mysql</database>
    </build>
</website>

Các thuộc tính trong XML sẽ được chuyển đổi thành gì nhỉ? Cùng xem kết quả của đoạn code bên dưới giúp chuyển đổi dữ liệu XML trong file info1.xml thành JSON để biết câu trả lời.

import xmltodict, json

# read file xml
with open("info1.xml") as file:
    data_xml = file.read()
# convert xml string to dictionary
data_dict = xmltodict.parse(data_xml)
# convert dictionary to json string
data_json = json.dumps(data_dict, indent=4)
# print xml string, dictionary, json string
print("type of data_xml:", type(data_xml))
print("type of data_dict:", type(data_dict))
print("type of data_json:", type(data_json))
print(data_json)
Kết quả
type of data_xml: <class 'str'>
type of data_dict: <class 'collections.OrderedDict'>
type of data_json: <class 'str'>
{
    "website": {
        "domainname": "gochocit.com",
        "active": "True",
        "numberposts": "360",
        "category": {
            "item": [
                {
                    "@post": "50",
                    "#text": "hardware"
                },
                {
                    "@post": "150",
                    "#text": "software"
                },
                {
                    "@post": "17",
                    "#text": "network"
                }
            ]
        },
        "facebookpage": "https://www.facebook.com/gochocit/",
        "build": {
            "language": "php",
            "cms": "wordpress",
            "database": "mysql"
        }
    }
}

Có thể thấy, thuộc tính post của tag item được chuyển thành key “@post” và text của tag item được chuyển thành key “#text“.

5/5 - (1 bình chọn)
Bài trước và bài sau trong môn học<< Ghi (write) file JSON với PythonChuyển đổi (convert) dữ liệu JSON sang dữ liệu XML 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ỏ.