1、 python读json文件(含中文)报错
报错:UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xcb in position 8: invalid continuation byte
解决方法:
读文件时 encoding=‘gbk’
json_file = 'try.json'
with open(json_file, "r", encoding='gbk') as file:
json_data = json.load(file)
2、 python写json文件后中文显示乱码
问题描述:中文显示为英文地址,如“\u56db"
问题原因:json dump 时 ensure_ascii为True时,所有非ASCII码字符显示为\uXXXX序列
解决方法:
json dump 时 ensure_ascii=False
new_dict = {'我':5, '你':4} # 要写入json的字典
new_json_file = 'new.json' # 要写入的json文件名
json_str = json.dumps(new_dict, indent=4, ensure_ascii=False)
with open(new_json_file, 'w', encoding='gbk') as json_file:
json_file.write(json_str)
3、Ubuntu系统 gedit打开json文件时中文显示为乱码
(参考 ubuntu wiki 及 CSDN)
Gedit 3.x 版本设置 (适用于Ubuntu 11.10及以后)
2种方法均可:
(1)命令方式:
gsettings set org.gnome.gedit.preferences.encodings auto-detected "['GB18030', 'UTF-8', 'CURRENT', 'ISO-8859-15', 'UTF-16']"
(2)图形方式:
sudo apt install dconf-editor
dconf-editor
展开/org/gnome/gedit/preferences/encodings,把“candidate-encodings”的值改为:
['GB18030', 'UTF-8', 'CURRENT', 'ISO-8859-15', 'UTF-16']