python
主页 > 脚本 > python >

python中json.dumps和json.dump区别

2025-01-01 | 佚名 | 点击:

1、json.dumps和json.dump的区别

json.dumps() 是将 Python 对象序列化为 JSON 格式的字符串。如果你想将 JSON 数据写入文件,可以将 json.dumps() 生成的字符串写入文件,或者更直接地使用 json.dump() 函数,它会直接将 Python 对象序列化写入文件。

下面是两个方法,一是使用 json.dumps() 然后写入文件,二是使用 json.dump() 直接写入文件。

2、使用 json.dumps() 然后写入文件

1

2

3

4

5

6

7

8

9

10

import json

 

data = {"name": "Alice", "age": 30, "is_student": False}

 

# 序列化为 JSON 字符串

json_str = json.dumps(data, indent=4)

 

# 将 JSON 字符串写入文件

with open('output.json', 'w', encoding='utf-8') as file:

    file.write(json_str)

3、使用 json.dump() 直接写入文件

1

2

3

4

5

6

7

import json

 

data = {"name": "Alice", "age": 30, "is_student": False}

 

# 直接将 JSON 数据写入文件

with open('output.json', 'w', encoding='utf-8') as file:

    json.dump(data, file, indent=4)

4、json.dump() 参数

1

2

3

4

5

6

import json

 

data = {"name": "Alice", "age": 30, "languages": ["English", "French"], "is_student": False}

 

with open('output.json', 'w', encoding='utf-8') as file:

    json.dump(data, file, indent=4, ensure_ascii=False, sort_keys=True)

json.dumps() 的参数可见博客json.dumps的参数

原文链接:
相关文章
最新更新