JSON是用于数据交换的轻量级数据格式,可以很容易地被人类读取和写入,也可以由机器轻松解析和生成。它是一种完全独立于语言的文本格式。为了处理JSON数据,Python有一个名为的内置包json。
示例:
s ='{“ id”:01,“ name”:“ Emily”,“ language”:[“ C ++”,“ Python”]}'JSON的语法被视为JavaScript语法的子集,包括以下内容:
名称/值对:代表数据,名称后跟':'(冒号),名称/值对以逗号分隔。
大括号:容纳对象。
方括号:保留由(,)分隔的值的数组。
键/名称必须是带双引号的字符串,值必须是以下类型的数据类型:
Str
列表
对象(JSON对象)
数组
布尔型
空值
例: { “员工”:[ { “ id”:“ 01”, “ name”:“ Amit”, “部门”:“销售” }, { “ id”:“ 04”, “ name”:“ sunil”, “部门”:“ HR” } ]}解析JSON(从JSON转换为Python)
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'}尼丁Python读取JSON文件
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的字典的方法来解析文件。
从Python转换为JSON
json.dumps() 方法可以将Python对象转换为JSON字符串。
句法:
json.dumps(dict,indent)它带有两个参数:
dictionary –字典的名称,应将其转换为JSON对象。
缩进–定义缩进单位数
# 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字符串:
字典
列表
元组
字符串
整型
浮动
True
False
NUll
Python对象及其等效的JSON转换:

将JSON写入文件
json.dump() 方法可用于写入JSON文件。
句法:
json.dump(dict,file_pointer)它包含2个参数:
dictionary –字典的名称,应将其转换为JSON对象。
文件指针–在写入或追加模式下打开的文件的指针。
# 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中。
在Python中初始化:您需要了解的一切
建立数据驱动,关键字驱动和混合Selenium框架这些你了解吗
如何在Selenium WebDriver中查找元素?(二)
如何在Selenium WebDriver中查找元素?(一)
python之函数基础
python接口测试—get请求
