python:Json模块dumps、loads、dump、load介绍,jsondumps,由上篇文章(pyth
python:Json模块dumps、loads、dump、load介绍,jsondumps,由上篇文章(pyth
由上篇文章(python3+requests:get/post请求)涉及到的json.dumps()扩展
1.json.dumps()用于将dict类型的数据转成str
备注:文件路径前面加上 r 是为了避免转义
1 import json 2 3 dict = {‘a‘: ‘wo‘, ‘b‘: ‘zai‘, ‘c‘: ‘zhe‘, ‘d‘: ‘li‘} 4 string = json.dumps(dict) 5 print(dict) 6 print(string) 7 print(type(dict)) 8 print(type(string)) 9 10 with open(r‘C:\Users\zy\Documents\GitHub\python3\searchTest\json.json‘,‘w‘)as f:11 f.write(string)
1 {‘a‘: ‘wo‘, ‘b‘: ‘zai‘, ‘c‘: ‘zhe‘, ‘d‘: ‘li‘}2 {"a": "wo", "b": "zai", "c": "zhe", "d": "li"}3 <class ‘dict‘>4 <class ‘str‘>
如果没有进行转换,则会报错:TypeError: write() argument must be str, not dict
1 import json2 3 dict = {‘a‘: ‘wo‘, ‘b‘: ‘zai‘, ‘c‘: ‘zhe‘, ‘d‘: ‘li‘}4 with open(r‘C:\Users\zy\Documents\GitHub\python3\searchTest\json.json‘,‘w‘)as f:5 f.write(dict)
1 {‘a‘: ‘wo‘, ‘b‘: ‘zai‘, ‘c‘: ‘zhe‘, ‘d‘: ‘li‘}2 Traceback (most recent call last):3 <class ‘dict‘>4 File "C:/Users/zy/Documents/GitHub/python3/searchTest/json_test.py", line 11, in <module>5 f.write(dict)6 TypeError: write() argument must be str, not dict
2.json.loads():用于将str类型的数据转成dict
1 dict = {‘a‘: ‘wo‘, ‘b‘: ‘zai‘, ‘c‘: ‘zhe‘, ‘d‘: ‘li‘} 2 dumps = json.dumps(dict) 3 loads = json.loads(dumps) 4 5 print(dict) 6 print(dumps) 7 print(loads) 8 9 print(type(dict))10 print(type(dumps))11 print(type(loads))
1 {‘a‘: ‘wo‘, ‘b‘: ‘zai‘, ‘c‘: ‘zhe‘, ‘d‘: ‘li‘}2 {"a": "wo", "b": "zai", "c": "zhe", "d": "li"}3 {‘a‘: ‘wo‘, ‘b‘: ‘zai‘, ‘c‘: ‘zhe‘, ‘d‘: ‘li‘}4 <class ‘dict‘>5 <class ‘str‘>6 <class ‘dict‘>
3.json.dump()用于将dict类型的数据转成str,并写入到json文件中
1 dict = {‘a‘: ‘wo‘, ‘b‘: ‘zai‘, ‘c‘: ‘zhe‘, ‘d‘: ‘li‘}2 json.dump(dict,open(r‘C:\Users\zy\Documents\GitHub\python3\searchTest\json.json‘,‘w‘))
4.json.load()用于从json文件中读取数据
1 filename = (r‘C:\Users\zy\Documents\GitHub\python3\searchTest\json.json‘)2 jsObj = json.load(open(filename))3 print(jsObj)4 print(type(jsObj))
1 {‘a‘: ‘wo‘, ‘b‘: ‘zai‘, ‘c‘: ‘zhe‘, ‘d‘: ‘li‘}2 <class ‘dict‘>
python:Json模块dumps、loads、dump、load介绍
相关内容
- 小甲鱼Python第十九讲课后习题,python十九讲课后,笔记:
- Python 和 Elasticsearch 构建简易搜索,,Python 和 E
- python3执行javaScript脚本,js2py教程,,简介:js2py安装
- Python3安装Pyyaml,python3pyyaml,转自:http://
- python eval()内置函数,,python有一个内
- 莫烦Python之机器学习概念了解,烦python机器概念,1、机
- Linux 安装python3.7.0,linuxpython3.7.0,我这里使用的时cen
- 12、python基础学习-for循环,12python基础-for, 1 #__auth
- python机器学习-sklearn挖掘乳腺癌细胞(五),,python机器
- 审计系统---堡垒机python下ssh的使用,,堡垒机python下
评论关闭