python json.dumps中文亂碼問(wèn)題解決
json.dumps(var,ensure_ascii=False)并不能解決中文亂碼的問(wèn)題
json.dumps在不同版本的Python下會(huì)有不同的表現(xiàn), 注意下面提到的中文亂碼問(wèn)題在Python3版本中不存在。
注:下面的代碼再python 2.7版本下測(cè)試通過(guò)
# -*- 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中沒(méi)有這種問(wèn)題,所以最簡(jiǎn)單的方法是引入__future__模塊,把新版本的特性導(dǎo)入到當(dāng)前版本
from __future__ import unicode_literalsprint json.dumps(odata,ensure_ascii=False)
結(jié)果:
{'a': '你好'}
在寫(xiě)入文件的時(shí)候出現(xiàn)了Python2.7的UnicodeEncodeError: ‘a(chǎn)scii’ codec can’t encode異常錯(cuò)誤
大神的解決方法:
不使用open打開(kāi)文件,而使用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中文亂碼問(wèn)題解決的文章就介紹到這了,更多相關(guān)python json.dumps中文亂碼內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. asp中response.write("中文")或者js中文亂碼問(wèn)題2. asp取整數(shù)mod 有小數(shù)的就自動(dòng)加13. CSS3中Transition屬性詳解以及示例分享4. 詳解盒子端CSS動(dòng)畫(huà)性能提升5. 利用CSS制作3D動(dòng)畫(huà)6. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?7. CSS hack用法案例詳解8. 怎樣打開(kāi)XML文件?xml文件如何打開(kāi)?9. css代碼優(yōu)化的12個(gè)技巧10. XML入門(mén)的常見(jiàn)問(wèn)題(二)
