如何将Python元组以JSON格式输出?


JSON可以缩写为**JavaScript 对象表示法**。它指的是一种编程语言中用于传输和存储数据的文本文件脚本。Python编程语言通过名为**json**的内置包支持它。

它的文本以带引号的字符串格式给出,包含在花括号{}中的键值对,看起来像字典。

要使用Python访问JSON文档,我们必须导入json包。在这个包中,我们有一个名为**dumps()**的方法,用于将Python元组对象转换为JSON对象。(原文有误,应为JSON对象,而非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日

912 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.