学堂 学堂 学堂公众号手机端

json.dumps()函数用于将Python对象编码为JSON格式的字符串。它的使用方式如下

lewis 1年前 (2024-04-15) 阅读数 11 #技术

json.dumps()函数用于将Python对象编码为JSON格式的字符串。它的使用方式如下:

importjson #创建一个Python对象 data={ "name":"John", "age":30, "city":"NewYork" } #使用json.dumps()将Python对象编码为JSON格式的字符串 json_string=json.dumps(data) #打印编码后的JSON字符串 print(json_string)

输出结果:

{"name":"John","age":30,"city":"NewYork"}

你可以通过指定一些参数来定制编码过程。例如,你可以使用indent参数来指定缩进的空格数量,使输出的JSON字符串更易读。示例如下:


importjson data={ "name":"John", "age":30, "city":"NewYork" } #使用indent参数指定缩进空格数量为4 json_string=json.dumps(data,indent=4) print(json_string)

输出结果:

{ "name":"John", "age":30, "city":"NewYork" }

除了indent参数外,json.dumps()函数还有其他一些可选参数,如sort_keysseparators等,可以根据需求进行设置。详细的使用方式可参考Python官方文档中的json.dumps()说明。

版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门