示例代码(在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)?
当前回答
下面是我使用json.dump()的解决方案:
def jsonWrite(p, pyobj, ensure_ascii=False, encoding=SYSTEM_ENCODING, **kwargs):
with codecs.open(p, 'wb', 'utf_8') as fileobj:
json.dump(pyobj, fileobj, ensure_ascii=ensure_ascii,encoding=encoding, **kwargs)
其中SYSTEM_ENCODING设置为:
locale.setlocale(locale.LC_ALL, '')
SYSTEM_ENCODING = locale.getlocale()[1]
其他回答
下面是我使用json.dump()的解决方案:
def jsonWrite(p, pyobj, ensure_ascii=False, encoding=SYSTEM_ENCODING, **kwargs):
with codecs.open(p, 'wb', 'utf_8') as fileobj:
json.dump(pyobj, fileobj, ensure_ascii=ensure_ascii,encoding=encoding, **kwargs)
其中SYSTEM_ENCODING设置为:
locale.setlocale(locale.LC_ALL, '')
SYSTEM_ENCODING = locale.getlocale()[1]
使用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进制字符串编解码问题
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"}
这是一个错误的答案,但了解为什么它是错误的仍然很有用。见注释。
使用unicode转义:
>>> d = {1: "ברי צקלה", 2: u"ברי צקלה"}
>>> json_str = json.dumps(d).decode('unicode-escape').encode('utf8')
>>> print json_str
{"1": "ברי צקלה", "2": "ברי צקלה"}
如果您正在从文件加载JSON字符串,并且文件内容是阿拉伯语文本,那么这将起作用。
假设像arabic.json这样的文件
{
"key1": "لمستخدمين",
"key2": "إضافة مستخدم"
}
从Arabic.json文件中获取阿拉伯语内容
with open(arabic.json, encoding='utf-8') as f:
# Deserialises it
json_data = json.load(f)
f.close()
# JSON formatted string
json_data2 = json.dumps(json_data, ensure_ascii = False)
要在Django模板中使用JSON数据,请执行以下步骤:
# If have to get the JSON index in a Django template file, then simply decode the encoded string.
json.JSONDecoder().decode(json_data2)
完成!现在,我们可以将结果作为一个带有阿拉伯值的JSON索引获得。