1.Python中加载JSON
使用loads(string):作用将string类型转为dict字典或dict链表
# 加载配置,configuration_path:配置文件路径 def load_conf(configuration_path): with open(configuration_path, 'r') as f: string = f.read() return json.loads(string)
使用load(file_stream):作用从文件流直接读取并转换为dict字典或dict字典链表
# 加载配置,configuration_path:配置文件路径 def load_conf(configuration_path): with open(configuration_path, 'r') as f: data = json.load(f) return data
2.Python写入JSON
使用dumps():将可以转换为json对象的对象转换为String,然后可通过字符流或字节流写入文件
def save_conf(confiuration_path, pre_trans_obj): #先用dunps转为string,然后字符流写入 #ensure_ascii=False, 减少乱码 json_string = json.dumps(pre_trans_obj, ensure_ascii=False) with open(confiuration_path,'w') as f: f.write(json_string)
使用dump():将可转为json对象的对象直接写入文件
def save_conf(confiuration_path, pre_trans_obj): with open('confiuration_path','w') as f: json.dump(pre_trans_obj, f, ensure_ascii=False)