如何在 Tkinter 中的 Python 函式中返回 JSON 物件?


JavaScript 物件表示法或 JSON 是一種簡單的資料格式,用於在許多不同的語言之間交換資料。它易於人們閱讀,也易於計算機解析。

Python 將 JSON 文字讀取為包含每個鍵值對映中值的帶引號的字串。解析後,它在 Python 中可作為字典物件訪問。JSON 資料可以使用 Python 中內建的 json 包進行編碼和解碼。您必須首先匯入 json 庫才能使用 json 型別的檔案。

Purposeco JSON

Python 到 JSON 的轉換是使用序列化完成的。將資料轉換為一系列位元組以進行儲存的過程稱為序列化。

不同的 Python 特定物件被轉換為標準的 JSON 可接受格式,因為 JSON 可以被其他語言讀取。例如,Python 特定的列表和元組在儲存為 JSON 格式時會更改為陣列。

將 JSON 物件匯入並解析為 Python dict 也適用相同規則。它儲存為“dict”,因為它具有與 JSON 非常相似的格式,並且可以包含其他資料結構,例如列表、元組和其他 dict 等。

要從 Python 函式返回 JSON 物件,您需要使用 dumps() 函式。

使用 dumps() 函式

當我們希望傳輸和儲存 Python 物件時,我們通常使用 dumps 函式,而 json 包使此任務快速且簡單。當物件必須以字串格式存在時,它用於解析、列印和其他函式。此方法直接寫入 json 檔案。

演算法

以下是從 Python 函式返回 json 物件的方法:

  • 匯入模組

  • 建立函式

  • 建立字典

  • 使用 dumps() 方法將字典轉換為 JSON 物件。

  • 返回 JSON 物件

注意 - 字典將被轉換為 JSON 字串並使用 json.dump() 儲存到檔案中。

示例

以下是上述方法的示例:

import json # Creating the function def sports(): # Defining the Variable name = "Cricket" player = "Sachin Tendulkar" Playerid = 13 score = 49 # Creating the dictionary values = { "name": name, "player": player, "Playerid": Playerid, "score": score } return json.dumps(values) # Calling the function and printing it print('The dictionary is:',sports())

輸出

以下是上述程式碼的輸出:

The dictionary is: {"name": "Cricket", "player": "Sachin Tendulkar", "Playerid": 13, "score": 49}

示例

以下是使用列表作為字典值的上述解釋方法的示例:

import json # Creating the function def sports(): # Creating the dictionary values = { "name": "Cricket", "player": "Hardik Pandya", "position": ["Batsman", "Bowler", "Fielder"], "Playerid": 13, "score": [{ "ODI match": 100, "T-20 match": 89, "Test match": 200 }, { "Asia Cup": 249, "ODI World Cup": 347, "IPL": 150 } ] } return json.dumps(values) # Calling the function and printing it print('The dictionary is:',sports())

輸出

以下是上述程式碼的輸出:

The dictionary is: {"name": "Cricket", "player": "Hardik Pandya", "position": ["Batsman", "Bowler", "Fielder"], "Playerid": 13, "score": [{"ODI match": 100, "T-20 match": 89, "Test match": 200}, {"Asia Cup": 249, "ODI World Cup": 347, "IPL": 150}]}

示例

藉助提供的 Python 字典,我們可以從 Python 函式返回 JSON 物件,如下所示:

import json dictionary = {'name':'Ananya', 'age': 23, 'isEmployed': True } # python dictionary def returnjson(): result = json.dumps(dictionary) print ('The dictionary is:',result) returnjson()

輸出

以下是上述程式碼的輸出:

The dictionary is: {"name": "Ananya", "age": 23, "isEmployed": true}

更新於: 2022-11-23

2K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告