python-操作json
操作json
loads
将字符串转换成python对象
import json str1 = '{"username": "marton", "psw": "123456"}' dict1 = json.loads(str1) print(dict1) #{'username': 'marton', 'psw': '123456'} print(type(dict1)) #<class 'dict'>
load
从文件中加载解析成一个python对象
user_info.json
{"user": "marton", "psw": "123456"}
import json dict1 = {"user": "marton", "psw": "123456"} with open('user_info.json') as f: dict1 = json.load(f) print(dict1) #{'user': 'marton', 'psw': '123456'} print(type(dict1)) #<class 'dict'>
dump
把一个python对象以json的形式写入文件
import json dict1 = {"user": "marton", "psw": "123456"} with open('user_info.json', 'w') as f: json.dump(dict1, f)
dumps
将一个python对象转换成json
import json dict1 = {"user": "marton", "psw": "123456"} str1 = json.dumps(dict1) print(str1) #{"user": "marton", "psw": "123456"} print(type(str1)) #<class 'str'>
对json操作进行封装
import json class OperateJson: """ 操作json """ def __init__(self, file_path=None): if file_path: self.file_path = file_path else: self.file_path = '../data_config/user.json' self.data = self.load_json_data() #读取json文件 def load_json_data(self): with open(self.file_path) as fp: data = json.load(fp) return data #根据键获取数据 def get_data(self, key): return self.data[key] #将数据写入json文件中 def write_data(self, data): with open('../data_config/cookie.json', 'w') as fp: json.dump(data, fp) if __name__ == '__main__': oper_json = OperateJson() oper_json.write_data({'cookie': '123456'})