如何將 JSON 資料轉換為 Python 元組?


JSON 資料轉換為 Python 元組的一種常見方法是使用 **json.loads()** 將 JSON 資料轉換為字典,然後使用 **dict.items()** 將其轉換為 Python 元組

根據我們的需求,還有其他幾種方法可以將 JSON 資料轉換為元組,其中一些方法如下所示。

  • 使用 json.loads()dict.items() 方法

  • 使用 json.loads 和 手動元組 構造

  • 巢狀結構的遞迴轉換

JSON 資料

例如,假設我們有一個 JSON 資料檔案 (data.json),其內容如下。

{
   "id": "file",
   "value": "File",
   "popup": {
      "menuitem": [
         {"value": "New", "onclick": "CreateNewDoc()"},
         {"value": "Open", "onclick": "OpenDoc()"},
         {"value": "Close", "onclick": "CloseDoc()"}
      ]
   }
}

使用 json.loads() 和 dict.items()

這是最常見的方法,它包括使用 **json.loads()** 方法將 JSON 載入為 Python 字典以解析 JSON 資料,然後使用 **.items()** 方法將該字典轉換為元組。

示例

在下面的示例程式碼中,**'with open('data.json') as f'** 定義以讀取模式開啟檔案 **data.json** 並將檔案物件分配給 f

import json

# Load JSON from a file
with open('data.json') as f:
    data = json.load(f)

# Convert the dictionary to a tuple
data_tuple = tuple(data.items())

print(data_tuple)

輸出

(('id', 'file'), ('value', 'File'), ('popup', {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}))

手動元組構造

透過使用這種方法,我們可以手動載入 JSON 並透過迭代字典來構造元組,它還提供了更多控制權來選擇要轉換為元組的 JSON 資料的部分。

示例

在下面的示例程式碼中,**'for key, value in data.items()'** 指的是手動迴圈遍歷字典,內部字典的處理是透過使用 **'if isinstance(value, dict)'** 完成的,如果是字典,則使用 **'tuple(value.items())'** 函式將其轉換為元組。

import json

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

# Create an empty list to store the tuples
data_tuple = []

# Manually loop through the dictionary and append key-value pairs as tuples
for key, value in data.items():
    if isinstance(value, dict):
        # Convert the inner dictionary into a tuple
        value = tuple(value.items())
    data_tuple.append((key, value))

# Convert the final list to a tuple
data_tuple = tuple(data_tuple)

print(data_tuple)

輸出

(('id', 'file'), ('value', 'File'), ('popup', (('menuitem', [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]))))

巢狀結構的遞迴轉換

此方法用於處理複雜的 **巢狀 JSON 結構**(例如陣列或巢狀物件),並且我們還可以遞迴地將字典和巢狀列表都轉換為元組。

示例

在下面的示例程式碼中,有兩個遞迴情況用於將物件(字典和列表)轉換為元組。

  • **遞迴情況 1(字典)**:使用 **'if isinstance(d, dict)'** 檢查物件是否為字典,如果是字典,則使用 **'dict_to_tuple'** 遞迴地將每個鍵值對轉換為元組。

  • **遞迴情況 2(列表)**:使用 **'elif isinstance(d, list)'** 檢查物件是否為列表,如果是列表,則使用 **'dict_to_tuple'** 將每個元素轉換為元組。

import json

def dict_to_tuple(d):
    # If the object is a dictionary, convert its items to tuples
    if isinstance(d, dict):
        return tuple((k, dict_to_tuple(v)) for k, v in d.items())
    # If the object is a list, convert each element to a tuple
    elif isinstance(d, list):
        return tuple(dict_to_tuple(x) for x in d)
    return d  # Base case: return the object as is if it's neither a dict nor a list

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

data_tuple = dict_to_tuple(data)
print(data_tuple)
(('id', 'file'), ('value', 'File'), ('popup', (('menuitem', (('value', 'New'), ('onclick', 'CreateNewDoc()')), (('value', 'Open'), ('onclick', 'OpenDoc()')), (('value', 'Close'), ('onclick', 'CloseDoc()'))))))

更新於: 2024-10-14

4K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.