一、josn常用操作方法
json.load:表示读取文件,返回python对象
json.dump:表示写入文件,文件为json字符串格式,无返回
json.dumps:将python中的字典类型转换为字符串类型,返回json字符串 [dict→str]
json.loads:将json字符串转换为字典类型,返回python对象 [str→dict]
load和dump处理的主要是 文件
loads和dumps处理的是 字符串
二、具体使用方法
1、json.loads()
import json
# json.loads()直接将json字符串并转换字典
json_str = """{
"memberId": "apple",
"tid": "cabbage"
}"""
py_dict = json.loads(json_str)
print(py_dict,type(py_dict))
{'memberId': 'apple', 'tid': 'cabbage'} <class 'dict'>
2、json.dumps()
import json
json_str = {
"memberId": "apple",
"tid": "cabbage"
}
# 将dict 转为josn
py_dict = json.dumps(json_str)
print(py_dict,type(py_dict))
{"memberId": "apple", "tid": "cabbage"} <class 'str'>
3、json.load()
with open(file,'r',encoding='utf-8') as f:
old_data = json.load(f)
4、json.dump()
with open(file,'w',encoding='utf-8') as f:
json.dump(old_data,f)