为什么python json.dumps抱怨ascii解码?

I Z*_*I Z 4 python json codec

我的代码中有以下几行

outs = codecs.getwriter('utf-8')(sys.stdout)
# dJSON contains JSON message with non-ASCII chars
outs.write(json.dumps(dJSON,encoding='utf-8', ensure_ascii=False, indent=indent_val))
Run Code Online (Sandbox Code Playgroud)

我收到以下异常:

    outs.write(json.dumps(dJSON,encoding='utf-8', ensure_ascii=False, indent=indent_val))
    File "/usr/lib/python2.7/json/__init__.py", line 238, in dumps
         **kw).encode(obj)
    File "/usr/lib/python2.7/json/encoder.py", line 204, in encode
         return ''.join(chunks)
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 27: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

我通过encoding='utf-8'json.dumps声明中指定,我避免了这种类型的问题.为什么我仍然收到错误?

Anu*_*yal 9

我的猜测是dJSON对象不包含纯unicode,但它包含unicode和已经编码的字符串的混合,utf-8例如,这会失败

>>> d = {u'name':u'?????'.encode('utf-8')}
>>> json.dumps(d, encoding='utf-8', ensure_ascii=False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 204, in encode
    return ''.join(chunks)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 1: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

但这工作(一切unicode)

>>> d = {u'name':u'?????'}
>>> json.dumps(d, encoding='utf-8', ensure_ascii=False)
u'{"name": "\u092a\u093e\u0907\u0925\u0928"}
Run Code Online (Sandbox Code Playgroud)

虽然这也有效(所有字符串)

>>> d = {'name':u'?????'.encode('utf-8')}
>>> json.dumps(d, encoding='utf-8', ensure_ascii=False)
'{"name": "\xe0\xa4\xaa\xe0\xa4\xbe\xe0\xa4\x87\xe0\xa4\xa5\xe0\xa4\xa8"}'
Run Code Online (Sandbox Code Playgroud)


d-d*_*d-d 5

有一个解决方法:将utf8编码(不是utf-8!)传递给 dumps 方法。在这种情况下,它将强制所有字符串首先解码unicode,并且您可以混合使用 unicode 字符串和已编码为 UTF-8 的字符串。为什么它有效?因为源码中有这么一句话JSONEncoder

if self.encoding != 'utf-8':
     def _encoder(o, _orig_encoder=_encoder, _encoding=self.encoding):
         if isinstance(o, str):
             o = o.decode(_encoding)
         return _orig_encoder(o)
Run Code Online (Sandbox Code Playgroud)

这就是我们所需要的,但它不能开箱即用。但是,当我们将编码更改为utf8(与 UTF-8 完全相同utf-8)时,我们会强制_encoder定义此编码,并且一切正常:)