JSON是用于数据交换的轻量级数据格式,可以很容易地被人类读取和写入,也可以由机器轻松解析和生成。它是一种完全独立于语言的文本格式。为了处理JSON数据,Python有一个名为的内置包json。
示例:
s ='{“ id”:01,“ name”:“ Emily”,“ language”:[“ C ++”,“ Python”]}'JSON的语法被视为JavaScript语法的子集,包括以下内容:
键/名称必须是带双引号的字符串,值必须是以下类型的数据类型:
例:
{
“员工”:[
{
“ id”:“ 01”,
“ name”:“ Amit”,
“部门”:“销售”
},
{
“ id”:“ 04”,
“ name”:“ sunil”,
“部门”:“ HR”
}
]
}json.loads() 方法可以解析json字符串,结果将是Python字典。
句法:
json.loads(json_string)例:
# Python program to convert JSON to Python
import json
# JSON string
employee ='{"id":"09", "name": "Nitin", "department":"Finance"}'
# Convert string to Python dict
employee_dict = json.loads(employee)
print(employee_dict)
print(employee_dict['name'])
输出:
{'id':'09','部门':'财务','名称':'Nitin'}
尼丁json.load()方法可以读取包含JSON对象的文件。考虑一个名为employee.json的文件,其中包含一个JSON对象。
句法:
json.load(file_object)示例:假设JSON如下所示。

我们想读取该文件的内容。下面是实现。
# Python program to read
# json file
import json
# Opening JSON file
f = open('data.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data['emp_details']:
print(i)
# Closing file
f.close()输出:

在这里,我们已使用该open()函数读取JSON文件。然后,使用json.load()提供给我们一个名为data的字典的方法来解析文件。
json.dumps() 方法可以将Python对象转换为JSON字符串。
句法:
json.dumps(dict,indent)它带有两个参数:
# Python program to convert
# Python to JSON
import json
# Data to be written
dictionary ={
"id": "04",
"name": "sunil",
"depatment": "HR"
}
# Serializing json
json_object = json.dumps(dictionary, indent = 4)
print(json_object)输出:
{
“部门”:“ HR”,
“ id”:“ 04”,
“名称”:“ sunil”
}可以将以下类型的Python对象转换为JSON字符串:
Python对象及其等效的JSON转换:

将JSON写入文件
json.dump() 方法可用于写入JSON文件。
句法:
json.dump(dict,file_pointer)它包含2个参数:
# 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)输出:

上面的程序使用“ w”以写入模式打开一个名为sample.json的文件。如果文件不存在,将创建该文件。Json.dump()会将字典转换为JSON字符串,并将其保存在文件sample.json中。