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': '\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對(duì)字符串是怎么處理的:
由于# -- coding: utf-8 --的作用,文件內(nèi)容以u(píng)tf-8編碼,所以print odata
輸出的是utf-8編碼后的結(jié)果
{‘a(chǎn)': ‘\xe4\xbd\xa0\xe5\xa5\xbd'}
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解碼是 浣犲ソ
字符串在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": "你好"}
在寫入文件的時(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 輸出中文亂碼問(wèn)題請(qǐng)查看下面的相關(guān)鏈接
- Python中json.dumps()函數(shù)使用和示例
- Python的json.loads() 方法與json.dumps()方法及使用小結(jié)
- Python中json.dumps()和json.dump()的區(qū)別小結(jié)
- python使用json.dumps輸出中文問(wèn)題
- python中json.dumps()和json.loads()的用法
- Python中json.dumps()函數(shù)的使用解析
- python json.dumps() json.dump()的區(qū)別詳解
- python json.dumps中文亂碼問(wèn)題解決
- python中json.dumps和json.dump區(qū)別
相關(guān)文章
Python3標(biāo)準(zhǔn)庫(kù)之dbm UNIX鍵-值數(shù)據(jù)庫(kù)問(wèn)題
dbm是面向DBM數(shù)據(jù)庫(kù)的一個(gè)前端,DBM數(shù)據(jù)庫(kù)使用簡(jiǎn)單的字符串值作為鍵來(lái)訪問(wèn)包含字符串的記錄。這篇文章主要介紹了Python3標(biāo)準(zhǔn)庫(kù):dbm UNIX鍵-值數(shù)據(jù)庫(kù)的相關(guān)知識(shí),需要的朋友可以參考下2020-03-03
pandas的object對(duì)象轉(zhuǎn)時(shí)間對(duì)象的方法
下面小編就為大家分享一篇pandas的object對(duì)象轉(zhuǎn)時(shí)間對(duì)象的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04
python數(shù)據(jù)結(jié)構(gòu)之鏈表詳解
這篇文章主要為大家詳細(xì)介紹了python數(shù)據(jù)結(jié)構(gòu)之鏈表的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09
Keras 數(shù)據(jù)增強(qiáng)ImageDataGenerator多輸入多輸出實(shí)例
這篇文章主要介紹了Keras 數(shù)據(jù)增強(qiáng)ImageDataGenerator多輸入多輸出實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07
在Python程序中實(shí)現(xiàn)分布式進(jìn)程的教程
這篇文章主要介紹了在Python程序中實(shí)現(xiàn)分布式進(jìn)程的教程,在多進(jìn)程編程中十分有用,示例代碼基于Python2.x版本,需要的朋友可以參考下2015-04-04

