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)
1.json.dumps()用于将dict类型的数据转成str
备注:文件路径前面加上 r 是为了避免转义
1 import json2
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
4
如果没有进行转换,则会报错: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
4 File "C:/Users/zy/Documents/GitHub/python3/searchTest/json_test.py", line 11, in
5 f.write(dict)
6 TypeError: write() argument must be str, not dict
json.dumps()参数解释:常用参数解释
indent:应该是一个非负的整型,如果是0,或者为空,则一行显示数据;否则会换行且按照indent的数量显示前面的空白
sort_keys:将数据根据keys的值进行排序
1 response = requests.post(url=url,headers=headers).json()2 print(json.dumps(response,sort_keys=True,indent=4))
举例结果:
1 {2 "code": "200",
3 "message": "",
4 "redirect": "",
5 "value": {
6 "name": "so",
7 "title": "360",
8 "value": "2"
9 }
10 }
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
5
6
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
常见问题:
1. json.dumps方法默认会输出成这种格式"\u535a\u5ba2\u56ed"
要输出中文需要指定ensure_ascii参数为False,如下代码片段:
json.dumps({'text':"中文"},ensure_ascii=False,indent=2) # indent 进行缩进展示