【问题标题】:getting a UnicodeEncodeError when trying to write a JSON file尝试写入 JSON 文件时出现 UnicodeEncodeError
【发布时间】:2013-07-15 22:48:26
【问题描述】:

给定输入文件的内容:

{ "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"
}

【问题讨论】:

标签: python python-unicode


【解决方案1】:

可以使用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)

【讨论】:

    猜你喜欢
    • 2011-10-19
    • 2014-03-05
    • 1970-01-01
    • 2020-04-25
    • 2016-12-21
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    相关资源
    最近更新 更多