json.dumps
函数用于将 Python 对象编码成 JSON 字符串。
json.dump
函数用于将 JSON 对象写入文件。
所以,主要区别是:
json.dumps
函数返回一个 JSON 字符串,可以用于在网络传输或者在 Python 程序中使用,但是不能直接写入文件。json.dump
函数直接将 JSON 对象写入文件,方便将数据保存在磁盘上,供程序使用。
两个函数的基本语法和用法类似,都是通过指定 Python 对象作为参数来调用的。
例如,下面是一个使用 json.dumps
函数的例子:
import json
data = {'name': 'John', 'age': 30, 'city': 'New York'}
json_data = json.dumps(data)
print(json_data)
输出结果为:
{"name": "John", "age": 30, "city": "New York"}
而下面是一个使用 json.dump
函数的例子:
import json
data = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('data.json', 'w') as f:
json.dump(data, f)
这样,就可以将 JSON 对象写入到文件 data.json
中了。