json文件经常被用来做一些数据间的映射配置,当出现中文时,普通的读写方式可能会产生乱码,可以尝试一下以下方式
写入
- 这里的class_dict是一个python字典类型
- json.dumps()可以将该python字典转换成字符串类型,返回json字符串
- 如果字典内不含中文,可以直接用以下代码写入
json_str = json.dumps(class_dict,indent=4)
with open('class.json', 'w') as json_file:
json_file.write(json_str)
- 如果字典中含有中文,则用以下代码,可以在json文件里正常显示
json_str = json.dumps(dict,ensure_ascii=False,indent=4)
with open('class.json', 'w',encoding='utf-8') as json_file:
json_file.write(json_str)
读取
- 若json文件不含中文,普通读取便可,如下代码
- json_path是json文件的路径
- json.load()函数是用来读取文件类型的数据,可以将json文件转成python的字典对象(注意和json.loads()函数不同,loads是来读取str字符串类型的数据,也是返回python对象)
with open(json_path, 'r') as f:
class_indict = json.load(f)
- 若json文件中含有中文,则用以下方式
with open(json_path, 'r',encoding='utf-8',errors='ignore') as f:
class_dict = json.load(f)
希望对你有所帮助