如何將 Python 元組以 JSON 格式輸出?
JSON 可以縮寫為 **JavaScript 物件表示法**。它表示一種程式語言中用於傳輸和儲存資料的文字檔案指令碼。Python 程式語言透過名為 **json** 的內建包來支援它。
它的文字以帶引號的字串格式給出,在花括號 {} 內包含鍵和值,看起來像字典。
要使用 Python 訪問 JSON 文件,我們必須匯入 json 包。在這個包中,我們有一個名為 **dumps()** 的方法,它用於將 Python 元組物件轉換為 Java 物件。
語法
以下是 **json** 包的 dumps 方法的語法。
variable_name = json.dumps(tuple)
示例
當我們將元組傳遞給 dumps() 函式時,元組資料將被轉儲為 JSON 格式。以下是程式碼。
import json tuple = (10,'python',True,20,30) json = json.dumps(tuple) print(json)
輸出
[10, "python", true, 20, 30]
示例
讓我們看另一個示例來了解將 Python 元組轉儲為 Json 格式的過程。
import json
tuple = (12, "Ravi", "B.Com FY", 78.50)
json = json.dumps(tuple)
print(json)
print("The type of the json format:",type(json))
輸出
[12, "Ravi", "B.Com FY", 78.5] The type of the json format: <class 'str'>
示例
如果我們希望檢索帶有空格的 JSON 文件,我們需要透過將可選引數 **indent** 設定為 **True** 來呼叫 dumps() 方法。
import json
tuple = (True,10,30,'python')
json = json.dumps(tuple, indent = True)
print(json)
print("The type of the json format:",type(json))
輸出
以下是 json 包 dumps 方法的輸出。在輸出中,我們可以看到轉換後的 JSON 格式和 json 格式的型別。json 輸出採用字串格式,並且元素按新行列印,因為我們將 indent 引數設定為 True。
[ true, 10, 30, "python" ] The type of the json format: <class 'str'>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP