python json.dumps中文亂碼問題解決
json.dumps(var,ensure_ascii=False)并不能解決中文亂碼的問題
json.dumps在不同版本的Python下會(huì)有不同的表現(xiàn), 注意下面提到的中文亂碼問題在Python3版本中不存在。
注:下面的代碼再python 2.7版本下測(cè)試通過
# -*- coding: utf-8 -*-odata = {’a’ : ’你好’}print odata
結(jié)果:
{’a’: ’xe4xbdxa0xe5xa5xbd’}
print json.dumps(odata)
結(jié)果:
{'a': 'u4f60u597d'}
print json.dumps(odata,ensure_ascii=False)
結(jié)果:
{'a': '浣?濂?}
print json.dumps(odata,ensure_ascii=False).decode(’utf8’).encode(’gb2312’)
結(jié)果:
{'a': '你好'}
要解決中文編碼,需要知道python2.7對(duì)字符串是怎么處理的:
由于# -- coding: utf-8 --的作用,文件內(nèi)容以u(píng)tf-8編碼,所以print odata
輸出的是utf-8編碼后的結(jié)果{‘a(chǎn)’: ‘xe4xbdxa0xe5xa5xbd’}
json.dumps 序列化時(shí)對(duì)中文默認(rèn)使用的ascii編碼, print json.dumps(odata)輸出unicode編碼的結(jié)果
print json.dumps(odata,ensure_ascii=False)不使用的ascii編碼,以gbk編碼
‘你好’ 用utf8編碼是 %E4%BD%A0%E5%A5%BD 用gbk解碼是 浣?濂?/p>
字符串在Python內(nèi)部的表示是unicode編碼。
因此,在做編碼轉(zhuǎn)換時(shí),通常需要以u(píng)nicode作為中間編碼,即先將其他編碼的字符串解碼(decode)成unicode,再?gòu)膗nicode編碼(encode)成另一種編碼。
decode的作用是將其他編碼的字符串轉(zhuǎn)換成unicode編碼
decode(’utf-8’)表示將utf-8編碼的字符串轉(zhuǎn)換成unicode編碼。
encode的作用是將unicode編碼轉(zhuǎn)換成其他編碼的字符串
encode(‘gb2312’),表示將unicode編碼的字符串轉(zhuǎn)換成gb2312編碼。
python3中沒有這種問題,所以最簡(jiǎn)單的方法是引入__future__模塊,把新版本的特性導(dǎo)入到當(dāng)前版本
from __future__ import unicode_literalsprint json.dumps(odata,ensure_ascii=False)
結(jié)果:
{'a': '你好'}
在寫入文件的時(shí)候出現(xiàn)了Python2.7的UnicodeEncodeError: ‘a(chǎn)scii’ codec can’t encode異常錯(cuò)誤
大神的解決方法:
不使用open打開文件,而使用codecs:
from __future__ import unicode_literalsimport codecsfp = codecs.open(’output.txt’, ’a+’, ’utf-8’)fp.write(json.dumps(m,ensure_ascii=False))fp.close()
到此這篇關(guān)于python json.dumps中文亂碼問題解決的文章就介紹到這了,更多相關(guān)python json.dumps中文亂碼內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. html中的form不提交(排除)某些input 原創(chuàng)2. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享3. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式4. jsp文件下載功能實(shí)現(xiàn)代碼5. 開發(fā)效率翻倍的Web API使用技巧6. ASP常用日期格式化函數(shù) FormatDate()7. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼8. CSS3中Transition屬性詳解以及示例分享9. asp.net core項(xiàng)目授權(quán)流程詳解10. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫特效
