您现在的位置是:网站首页>列表内容
python字典保存为json后读取出错问题及解决_python_
2025-08-26 09:45:28
8294人已围观
简介 python字典保存为json后读取出错问题及解决_python_
python字典保存为json后读取出错
json.load()读取json文件数据时,报错:XXXXXXXXX。
是因为在json文件中的引号为单引号,json.load()只能识别双引号。
避免报错的方式有三种
1、从保存文件时入手,刚开始就避免json文件中写入单引号。
json文件之所以写入单引号,大概率是在写入数据时,直接str(dict_data)字典转字符串,这种遗留问题就是不能用json.load()读取,写的时候应该用:json.dump(dict_data,file),一次写入到json文件中的字典是双引号的。
2、如果不想更换写入方式,或者数据是别人的,难么可以换读取方式。使用内置模块ast的literal_eval方法:
import ast ast.literal_eval(string)
3、直接使用python内置函数eval(string)
2和3的方法可以直接把字符串形式的json数据转为字典。
json文件转为str出现中文乱码问题
原来的代码是这样的
with open(fileName,'w',encoding='utf-8') as f: json.dump(AllResume,f)
当然用
temp = json.dumps(AllResume) with open(fileName,'w',encoding='utf-8') as f: f.write(temp) f.close()
得到的也是一样的结果。
出现的结果如下:

这是因为json.dumps或者json.dump 序列化时对中文默认使用的ascii编码,想输出真正的中文需要指定ensure_ascii=False:
with open(fileName,'w',encoding='utf-8') as f: json.dump(AllResume,f,ensure_ascii=False)
此时得到的结果才是:

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
点击排行
- pandas如何获取某个数据的行号_python_
- python进程池Pool中apply方法与apply_async方法的区别_python_
- python array中关于[a,b,c]的使用方式_python_
- Python进程multiprocessing.Process()的使用解读_python_
- selenium常用API的使用过程记录(包括自动登录)_python_
- Python使用multiprocessing如何实现多进程_python_
- pandas报错AttributeError: DataFrame object has no attribute ix问题_python_
- python模拟登陆、POST/GET请求方式_python_
- 解决Windows下PowerShell无法进入Python虚拟环境问题_python_
本栏推荐
-
pandas如何获取某个数据的行号_python_
-
python进程池Pool中apply方法与apply_async方法的区别_python_
-
python array中关于[a,b,c]的使用方式_python_
-
Python进程multiprocessing.Process()的使用解读_python_
-
selenium常用API的使用过程记录(包括自动登录)_python_
-
Python使用multiprocessing如何实现多进程_python_
-
pandas报错AttributeError: DataFrame object has no attribute ix问题_python_
-
python模拟登陆、POST/GET请求方式_python_
-
解决Windows下PowerShell无法进入Python虚拟环境问题_python_



