python json.dumps中文亂碼問題解決
json.dumps(var,ensure_ascii=False)并不能完全解決中文亂碼的問題
json.dumps在不同版本的Python下會有不同的表現(xiàn), 注意下面提到的中文亂碼問題在Python3版本中不存在。
注:下面的代碼再python 2.7版本下測試通過
# -*- coding: utf-8 -*-odata = {'a' : '你好'}print odata
結(jié)果:
{'a': '\xe4\xbd\xa0\xe5\xa5\xbd'}
print json.dumps(odata)
結(jié)果:
{"a": "\u4f60\u597d"}
print json.dumps(odata,ensure_ascii=False)
結(jié)果:
{"a": "浣犲ソ"}
print json.dumps(odata,ensure_ascii=False).decode('utf8').encode('gb2312')
結(jié)果:
{"a": "你好"}
要解決中文編碼,需要知道python2.7對字符串是怎么處理的:
由于# -- coding: utf-8 --的作用,文件內(nèi)容以utf-8編碼,所以print odata
輸出的是utf-8編碼后的結(jié)果
{‘a(chǎn)': ‘\xe4\xbd\xa0\xe5\xa5\xbd'}
json.dumps 序列化時對中文默認使用的ascii編碼, print json.dumps(odata)輸出unicode編碼的結(jié)果
print json.dumps(odata,ensure_ascii=False)不使用的ascii編碼,以gbk編碼
‘你好' 用utf8編碼是 %E4%BD%A0%E5%A5%BD 用gbk解碼是 浣犲ソ
字符串在Python內(nèi)部的表示是unicode編碼。
因此,在做編碼轉(zhuǎn)換時,通常需要以unicode作為中間編碼,即先將其他編碼的字符串解碼(decode)成unicode,再從unicode編碼(encode)成另一種編碼。
decode的作用是將其他編碼的字符串轉(zhuǎn)換成unicode編碼
decode('utf-8')表示將utf-8編碼的字符串轉(zhuǎn)換成unicode編碼。
encode的作用是將unicode編碼轉(zhuǎn)換成其他編碼的字符串
encode(‘gb2312')表示將unicode編碼的字符串轉(zhuǎn)換成gb2312編碼。
python3中沒有這種問題,所以最簡單的方法是引入__future__模塊,把新版本的特性導(dǎo)入到當(dāng)前版本
from __future__ import unicode_literalsprint json.dumps(odata,ensure_ascii=False)
結(jié)果:
{"a": "你好"}
在寫入文件的時候出現(xiàn)了Python2.7的UnicodeEncodeError: ‘a(chǎn)scii' codec can't encode異常錯誤
大神的解決方法:
不使用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 輸出中文亂碼問題請查看下面的相關(guān)鏈接
- Python中json.dumps()函數(shù)使用和示例
- Python的json.loads() 方法與json.dumps()方法及使用小結(jié)
- Python中json.dumps()和json.dump()的區(qū)別小結(jié)
- python使用json.dumps輸出中文問題
- python中json.dumps()和json.loads()的用法
- Python中json.dumps()函數(shù)的使用解析
- python json.dumps() json.dump()的區(qū)別詳解
- python json.dumps中文亂碼問題解決
- python中json.dumps和json.dump區(qū)別
相關(guān)文章
Python3標(biāo)準(zhǔn)庫之dbm UNIX鍵-值數(shù)據(jù)庫問題
dbm是面向DBM數(shù)據(jù)庫的一個前端,DBM數(shù)據(jù)庫使用簡單的字符串值作為鍵來訪問包含字符串的記錄。這篇文章主要介紹了Python3標(biāo)準(zhǔn)庫:dbm UNIX鍵-值數(shù)據(jù)庫的相關(guān)知識,需要的朋友可以參考下2020-03-03
pandas的object對象轉(zhuǎn)時間對象的方法
下面小編就為大家分享一篇pandas的object對象轉(zhuǎn)時間對象的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
python數(shù)據(jù)結(jié)構(gòu)之鏈表詳解
這篇文章主要為大家詳細介紹了python數(shù)據(jù)結(jié)構(gòu)之鏈表的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09
Keras 數(shù)據(jù)增強ImageDataGenerator多輸入多輸出實例
這篇文章主要介紹了Keras 數(shù)據(jù)增強ImageDataGenerator多輸入多輸出實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07

