如何将 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'>

更新于: 2023年5月15日

910 次浏览

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.