Step1:Json是什么
JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。具有数据格式简单,读写方便易懂等很多优点。
许多主流的编程语言都在用它来进行前后端的数据传输,大大的简化了服务器和客户端的开发工作量。相对于 XML 来说,更加的轻量级,更方便解析,因此许多开发者都遵循 Json 格式来进行数据的传输和交换。
Json 的数据格式其实就是 Python 里面的字典格式,里面可以包含方括号括起来的数组,也就是 Python 里面的列表。
Step2:Json 模块的四个方法
-
dumps():将dict数据转化成json数据(Python里是str类型)
-
loads():将json数据转化成dict数据(Python里是dict类型)
-
load():读取json文件数据,转成dict数据
-
dump():将dict数据转化成json数据后写入json文件
Step3:Python代码实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38import json def dict_to_json(): dict1={} dict1['name']='tom' dict1['age']=20 dict1['sex']='male' print(dict1) jsons=json.dumps(dict1) print(jsons) print(type(jsons)) def json_to_dict(): jsons = '{"name": "tony", "age": 28, "sex": "male", "phone": "123456", "email": "loadkernel@126.com"}' dict1= json.loads(jsons) print(dict1) print(type(dict1)) def dict_to_json_write_file(): dict = {} dict['name'] = 'tom' dict['age'] = 10 dict['sex'] = 'male' print(dict) with open('test.json', 'w') as f: json.dump(dict, f) def json_file_to_dict(): with open('test.json', 'r') as f: dict1 = json.load(f) print(dict1) print(type(dict1)) if __name__ == '__main__': dict_to_json() json_to_dict() dict_to_json_write_file() json_file_to_dict()
运行结果如下:
1
2
3
4
5
6
7
8{'name': 'tom', 'age': 20, 'sex': 'male'} {"name": "tom", "age": 20, "sex": "male"} <class 'str'> {'name': 'tony', 'age': 28, 'sex': 'male', 'phone': '123456', 'email': 'loadkernel@126.com'} <class 'dict'> {'name': 'tom', 'age': 10, 'sex': 'male'} {'name': 'tom', 'age': 10, 'sex': 'male'} <class 'dict'>
欢迎关注【无量测试之道】公众号,回复【领取资源】
Python编程学习资源干货、
Python+Appium框架APP的UI自动化、
Python+Selenium框架Web的UI自动化、
Python+Unittest框架API自动化、
资源和代码 免费送啦~
文章下方有公众号二维码,可直接微信扫一扫关注即可。
备注:我的个人公众号已正式开通,致力于测试技术的分享,包含:大数据测试、功能测试,测试开发,API接口自动化、测试运维、UI自动化测试等,微信搜索公众号:“无量测试之道”,或扫描下方二维码:
添加关注,让我们一起共同成长!
最后
以上就是高挑夕阳最近收集整理的关于Python之Json模块详解的全部内容,更多相关Python之Json模块详解内容请搜索靠谱客的其他文章。
发表评论 取消回复