Json模块dumps、loads、dump、load介绍
1.json.dumps()用于将dict类型的数据转成str
备注:文件路径前面加上 r 是为了避免转义
import json
dict = {'a': 'wo', 'b': 'zai', 'c': 'zhe', 'd': 'li'}
string = json.dumps(dict)
print(dict)
print(string)
print(type(dict))
print(type(string))
with open(r'C:\Users\zy\Documents\GitHub\python3\searchTest\json.json','w')as f:
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 json
2
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)
{'a': 'wo', 'b': 'zai', 'c': 'zhe', 'd': 'li'}
Traceback (most recent call last):
<class 'dict'>
File "C:/Users/zy/Documents/GitHub/python3/searchTest/json_test.py", line 11, in <module>
f.write(dict)
TypeError: write() argument must be str, not dict
json.dumps()参数解释:常用参数解释
indent:应该是一个非负的整型,如果是0,或者为空,则一行显示数据;否则会换行且按照indent的数量显示前面的空白
sort_keys:将数据根据keys的值进行排序
response = requests.post(url=url,headers=headers).json()
print(json.dumps(response,sort_keys=True,indent=4))
举例:
{
"code": "200",
"message": "",
"redirect": "",
"value": {
"name": "so",
"title": "360",
"value": "2"
}
}
2.json.loads():用于将str类型的数据转成dict
dict = {'a': 'wo', 'b': 'zai', 'c': 'zhe', 'd': 'li'}
dumps = json.dumps(dict)
loads = json.loads(dumps)
print(dict)
print(dumps)
print(loads)
print(type(dict))
print(type(dumps))
print(type(loads))
{'a': 'wo', 'b': 'zai', 'c': 'zhe', 'd': 'li'}
{"a": "wo", "b": "zai", "c": "zhe", "d": "li"}
{'a': 'wo', 'b': 'zai', 'c': 'zhe', 'd': 'li'}
<class 'dict'>
<class 'str'>
<class 'dict'>
3.json.dump()用于将dict类型的数据转成str,并写入到json文件中
dict = {'a': 'wo', 'b': 'zai', 'c': 'zhe', 'd': 'li'}
json.dump(dict,open(r'C:\Users\zy\Documents\GitHub\python3\searchTest\json.json','w'))
4.json.load()用于从json文件中读取数据
filename = (r'C:\Users\zy\Documents\GitHub\python3\searchTest\json.json')
jsObj = json.load(open(filename))
print(jsObj)
print(type(jsObj))
{'a': 'wo', 'b': 'zai', 'c': 'zhe', 'd': 'li'}
<class 'dict'>