如何将Python字典转换为 JSON?
JSON 代表 JavaScript 对象表示法。这意味着由编程语言中的文本组成的脚本(可执行)文件用于存储和传输数据。 Python通过一个名为 json 的内置包支持 JSON。要使用此功能,我们在Python脚本中导入 JSON 包。 JSON 中的文本是通过引用字符串完成的,该字符串包含 { } 内键值映射中的值。它类似于Python中的字典。
注意:有关详细信息,请参阅使用Python读取、写入和解析 JSON
使用的函数:
- json.dumps()
- json.dump()
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
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.
示例 1:
Python3
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
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)
输出
{
"id": "04",
"name": "sunil",
"department": "HR"
}
输出:
{
"department": "HR",
"id": "04",
"name": "sunil"
}
示例 2:
Python3
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)
输出: