json.dumps() 是 Python 中 json 模块的一个函数,用于将 Python 对象编码为 JSON 格式的字符串。这个函数非常有用,当你需要将 Python 对象保存为 JSON 文件,或者通过网络传输到另一个系统时,它可以很方便地将 Python 数据结构转换为 JSON 格式。
| import json |
| |
| |
| my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'} |
| |
| |
| 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 |
| |
| |
| my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'} |
| |
| |
| 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" |
| } |
复制