示例代码(在REPL中):
import json
json_string = json.dumps("ברי צקלה")
print(json_string)
输出:
"\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4"
问题是:它不是人类可读的。我的(智能)用户希望使用JSON转储来验证甚至编辑文本文件(我宁愿不使用XML)。
是否有方法将对象序列化为UTF-8 JSON字符串(而不是\uXXXX)?
示例代码(在REPL中):
import json
json_string = json.dumps("ברי צקלה")
print(json_string)
输出:
"\u05d1\u05e8\u05d9 \u05e6\u05e7\u05dc\u05d4"
问题是:它不是人类可读的。我的(智能)用户希望使用JSON转储来验证甚至编辑文本文件(我宁愿不使用XML)。
是否有方法将对象序列化为UTF-8 JSON字符串(而不是\uXXXX)?
当前回答
如果可能,请使用编解码器,
with codecs.open('file_path', 'a+', 'utf-8') as fp:
fp.write(json.dumps(res, ensure_ascii=False))
其他回答
写入文件的步骤
import codecs
import json
with codecs.open('your_file.txt', 'w', encoding='utf-8') as f:
json.dump({"message":"xin chào việt nam"}, f, ensure_ascii=False)
打印到标准输出
import json
print(json.dumps({"message":"xin chào việt nam"}, ensure_ascii=False))
Pieters的Python 2解决方案在边缘情况下失败:
d = {u'keyword': u'bad credit \xe7redit cards'}
with io.open('filename', 'w', encoding='utf8') as json_file:
data = json.dumps(d, ensure_ascii=False).decode('utf8')
try:
json_file.write(data)
except TypeError:
# Decode data to Unicode first
json_file.write(data.decode('utf8'))
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 25: ordinal not in range(128)
它在第3行的.decode('utf8')部分崩溃。我通过避免该步骤以及ASCII的特殊外壳,使程序更简单,从而解决了这个问题:
with io.open('filename', 'w', encoding='utf8') as json_file:
data = json.dumps(d, ensure_ascii=False, encoding='utf8')
json_file.write(unicode(data))
cat filename
{"keyword": "bad credit çredit cards"}
从Python 3.7开始,以下代码工作正常:
from json import dumps
result = {"symbol": "ƒ"}
json_string = dumps(result, sort_keys=True, indent=2, ensure_ascii=False)
print(json_string)
输出:
{"symbol": "ƒ"}
使用unicode转义解决问题
>>>import json
>>>json_string = json.dumps("ברי צקלה")
>>>json_string.encode('ascii').decode('unicode-escape')
'"ברי צקלה"'
解释
>>>s = '漢 χαν хан'
>>>print('Unicode: ' + s.encode('unicode-escape').decode('utf-8'))
Unicode: \u6f22 \u03c7\u03b1\u03bd \u0445\u0430\u043d
>>>u = s.encode('unicode-escape').decode('utf-8')
>>>print('Original: ' + u.encode("utf-8").decode('unicode-escape'))
Original: 漢 χαν хан
原始资源:Python3使用 unicode转义处理 unicode 16进制字符串编解码问题
这是一个错误的答案,但了解为什么它是错误的仍然很有用。见注释。
使用unicode转义:
>>> d = {1: "ברי צקלה", 2: u"ברי צקלה"}
>>> json_str = json.dumps(d).decode('unicode-escape').encode('utf8')
>>> print json_str
{"1": "ברי צקלה", "2": "ברי צקלה"}