Python處理JSON時的值報錯及編碼報錯的兩則解決實錄,pythonjson

來源:互聯網
上載者:User

Python處理JSON時的值報錯及編碼報錯的兩則解決實錄,pythonjson

1、ValueError: Invalid control character at: line 1 column 8363 (char 8362)
使用json.loads(json_data)時,出現:

ValueError: Invalid control character at: line 1 column 8363 (char 8362)

出現錯誤的原因是字串中包含了斷行符號符(\r)或者分行符號(\n)
解決方案:
(1)對這些字元轉義:

json_data = json_data.replace('\r', '\\r').replace('\n', '\\n')

(2)使用關鍵字strict:

json.loads(json_data, strict=False)

strict預設是True,它將嚴格控制內部字串,將其設定為False,便可以允許你\n \r。


2、UnicodeEncodeError: ascii codec can't encode錯誤
在windows下寫的python指令碼,放到linux下運行,直接報:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-11: ordinal not in range(128)

出錯原因是Python2.7在安裝時,預設的編碼是ascii,當程式中出現非ascii編碼時,Python的處理常常會報這樣的錯,不過在Python3中就不會有這樣的問題。
解決方案:
(1)臨時解決方案:
在代碼前加入:
import sys reload(sys) sys.setdefaultencoding('utf8')

(2)一勞永逸:
在Python的lib\site-packages檔案夾下建立一個sitecustomize.py,內容如下:

# encoding=utf8 import sys reload(sys) sys.setdefaultencoding('utf8')

這樣的話,系統在Python啟動的時候,自行調用該檔案,設定系統的預設編碼。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.