Python中的JSON:OS X上的编码问题,在Windows上没有问题

时间:2015-06-17 04:13:38

标签: python json windows macos encoding

我有一个文件log.json,其中包含一行:

{"k":"caf\u00e9"}

我在Windows 7 SP1 x64 Ultimate上运行以下代码:

import json 
a = json.load(open('log.json', 'r'))
f = open('test.txt', 'w')
f.write(a['k'])

我没有任何问题。

当我在Max OS X 10.10 x64上运行相同的代码时:

Traceback (most recent call last):
  File "/Users/francky/Documents/workspace/test.py", line 4, in <module>
    f.write(a['k'])
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 3: ordinal not in range(128)

它是如何在Windows上正常工作但在OS X上没有?

Python解释器的版本以及JSON Python包的版本在两个操作系统上是相同的:

import json 
import sys
print json.__version__
print(sys.version)

在OS X上返回:

2.0.9
2.7.6 (default, Sep  9 2014, 15:04:36) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)]

并在Windows上:

2.0.9
2.7.6 (default, Nov 10 2013, 19:24:24) [MSC v.1500 64 bit (AMD64)]

罪魁祸首是PyDev,used to use the Eclipse workspace or project setting "Text file encoding" and sets this as the Python default encoding(在PyDev 3.4.0及之后修复)。

并且为了支持一些非ASCII的查询,我将Python文件切换为UTF-8:

enter image description here

导致Python的sys.getdefaultencoding()UTF-8

enter image description here

仅供参考:Dangers of sys.setdefaultencoding('utf-8')

1 个答案:

答案 0 :(得分:1)

我在Windows上出现OSX故障, 应该失败,因为将Unicode字符串写入文件需要编码。当您将Unicode字符串写入文件时,Python 2将使用默认的ascii编解码器将其隐式转换为字节字符串,而对于非ASCII字符则会失败。你确定你在运行Python 2.7吗? Python 3没有错误。 io.open是Python 2上的{3}等效的{3},默认使用open。以下是修复Python 2的方法:

sys.getfilesystemencoding()

您可以选择为输出指定所需的确切编码作为附加参数:

import json
import io
data = r'{"k":"caf\u00e9"}'
a = json.loads(data)
with io.open('test.txt','w') as f:
    f.write(a['k'])