json.dumps()函数用于将Python对象编码为JSON格式的字符串。它的使用方式如下:
import json # 创建一个Python对象 data = https://www.yisu.com/ask/{"name": "John", "age": 30, "city": "New York" } # 使用json.dumps()将Python对象编码为JSON格式的字符串 json_string = json.dumps(data) # 打印编码后的JSON字符串 print(json_string)
输出结果:
{"name": "John", "age": 30, "city": "New York"}
你可以通过指定一些参数来定制编码过程。例如,你可以使用indent
参数来指定缩进的空格数量,使输出的JSON字符串更易读。示例如下:
import json data = https://www.yisu.com/ask/{"name": "John", "age": 30, "city": "New York" } # 使用indent参数指定缩进空格数量为4 json_string = json.dumps(data, indent=4) print(json_string)
输出结果:
{ "name": "John", "age": 30, "city": "New York" }
除了indent
参数外,json.dumps()
函数还有其他一些可选参数,如sort_keys
、separators
等,可以根据需求进行设置。详细的使用方式可参考Python官方文档中的json.dumps()说明。