簡體   English   中英

嘗試編寫JSON文件時獲取UnicodeEncodeError

[英]getting a UnicodeEncodeError when trying to write a JSON file

給定內容的輸入文件:

{ "symbol": "°C" }

這段代碼:

import sys
import json

with open(sys.argv[1], 'r') as ifile, open(sys.argv[2], 'w') as ofile:
    json.dump(json.load(ifile), ofile, indent=4, ensure_ascii=False)

我收到一個錯誤:

$ python2.7 play.py input.json output.json
Traceback (most recent call last):
  File "play.py", line 5, in <module>
    json.dump(json.load(ifile), ofile, indent=4, ensure_ascii=False)
  File "/usr/lib/python2.7/json/__init__.py", line 190, in dump
    fp.write(chunk)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb0' in position 1: ordinal not in range(128)

但Python 3工作正常:

$ python3.3 play.py input.json output.json
$ cat output.json 
{
    "symbol": "°C"
}

您可以使用codecs模塊通過聲明文件的編碼來處理它:

import sys
import json
import codecs

with codecs.open(sys.argv[1], 'r', 'utf-8') as ifile, codecs.open(sys.argv[2], 'w', 'utf-8') as ofile:
    json.dump(json.load(ifile), ofile, indent=4, ensure_ascii=False)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM