Python – json.dump() 和 json.dumps() 之间的区别
JSON 是一种用于数据交换的轻量级数据格式,人类易于读写,机器易于解析和生成。它是一种完全独立于语言的文本格式。为了处理 JSON 数据, Python有一个名为json
的内置包。
注意:有关更多信息,请参阅在Python中使用 JSON 数据
json.dumps()
json.dumps()
方法可以将Python对象转换为 JSON字符串。
Syntax: json.dumps(dict, indent)
Parameters:
- dictionary – name of dictionary which should be converted to JSON object.
- indent – defines the number of units for indentation
例子:
Python3
# Python program to convert
# Python to JSON
import json
# Data to be written
dictionary ={
"id": "04",
"name": "sunil",
"department": "HR"
}
# Serializing json
json_object = json.dumps(dictionary, indent = 4)
print(json_object)
Python3
# Python program to write JSON
# to a file
import json
# Data to be written
dictionary ={
"name" : "sathiyajith",
"rollno" : 56,
"cgpa" : 8.6,
"phonenumber" : "9976770500"
}
with open("sample.json", "w") as outfile:
json.dump(dictionary, outfile)
输出:
{
"department": "HR",
"id": "04",
"name": "sunil"
}
Python对象及其到 JSON 的等效转换:
Python | JSON Equivalent |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float | number |
True | true |
False | false |
None | null |
json.dump()
json.dump()
方法可用于写入 JSON 文件。
Syntax: json.dump(dict, file_pointer)
Parameters:
- dictionary – name of dictionary which should be converted to JSON object.
- file pointer – pointer of the file opened in write or append mode.
例子:
Python3
# Python program to write JSON
# to a file
import json
# Data to be written
dictionary ={
"name" : "sathiyajith",
"rollno" : 56,
"cgpa" : 8.6,
"phonenumber" : "9976770500"
}
with open("sample.json", "w") as outfile:
json.dump(dictionary, outfile)
输出: