本文實例講述了Python實現(xiàn)的json文件讀取及中文亂碼顯示問題解決方法。分享給大家供大家參考,具體如下:
city.json文件的內(nèi)容如下:
{ "cities": [ { "city": "北京", "cityid": "101010100" }, { "city": "上海", "cityid": "101020100" } ]}可見,其中包含了中文。
Python使用json.loads之后打印中文會出現(xiàn)亂碼的問題,解決方法如下:
with open('city.json', 'r') as json_file: """ 讀取該json文件時,先按照gbk的方式對其解碼再編碼為utf-8的格式 """ data = json_file.read().decode(encoding='gbk').encode(encoding='utf-8') print type(data) # type(data) = 'str' result = json.loads(data) new_result = json.dumps(result,ensure_ascii=False) # 參考網(wǎng)上的方法,***ensure_ascii***設(shè)為False print new_result# 輸出結(jié)果:# "cities": [{"cityid": "101010100", "city": "北京"}, {"cityid": "101020100", "city": "上海"}]PS:這里再為大家推薦幾款比較實用的json在線工具供大家參考使用:
在線JSON代碼檢驗、檢驗、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在線格式化工具:
http://tools.jb51.net/code/jsonformat
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
json代碼在線格式化/美化/壓縮/編輯/轉(zhuǎn)換工具:
http://tools.jb51.net/code/jsoncodeformat
在線json壓縮/轉(zhuǎn)義工具:
http://tools.jb51.net/code/json_yasuo_trans
更多Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python操作json技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
新聞熱點
疑難解答