Python 尝试编写JSON文件时获取UnicodeError

Python 尝试编写JSON文件时获取UnicodeError,python,python-unicode,Python,Python Unicode,给定包含内容的输入文件: { "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.

给定包含内容的输入文件:

{ "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)
您可以使用模块通过声明文件的编码来处理它:

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)
可能重复的
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)