json.dumps()函数使用和示例
json.dumps() 是 python 中 json 模块的一个函数
用于将 python 对象编码为 json 格式的字符串
这个函数非常有用
当你需要将 python 对象保存为 json 文件
或者通过网络传输到另一个系统时
它可以很方便地将 python 数据结构转换为 json 格式
import json # 创建一个 python 字典 my_dict = {'name': 'alice', 'age': 30, 'city': 'new york'} # 使用 json.dumps() 将字典转换为 json 格式的字符串 json_string = json.dumps(my_dict) print(json_string)
输出:
{"name": "alice", "age": 30, "city": "new york"}
json.dumps()函数还有一些其他参数
例如:
indent
:用于设置输出的 json 字符串的缩进层次,使其更易读。sort_keys
:用于设置是否要对字典的键进行排序。ensure_ascii
:用于设置是否仅使用 ascii 字符。escape_forward_slashes
:用于设置是否要转义正斜杠 /。
import json # 创建一个 python 字典 my_dict = {'name': 'alice', 'age': 30, 'city': 'new york'} # 使用 json.dumps() 将字典转换为 json 格式的字符串 json_string = json.dumps(my_dict) print(json_string) json_string = json.dumps(my_dict, indent=4, sort_keys=true) print(json_string)
输出:
{"name": "alice", "age": 30, "city": "new york"}
{
"age": 30,
"city": "new york",
"name": "alice"
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论