我有以下用例:
我从数据中生成一个带有数据的 json,其中一部分是希伯来语单词。 例如:
import json
j = {}
city =u'חיפה' #native unicode
j['results']= []
j['results'].append({'city':city}) #Also tried to city.encode('utf-8') and other encodings
为了生成一个兼作我的应用程序数据库(微型地理应用程序)的 json 文件,并作为我的用户可以直接编辑和修复数据的文件,我使用了 json 库和:
to_save = json.dumps(j)
with open('test.json','wb') as f: #also tried with w instead of wb flag.
f.write(to_save)
f.close()
问题是我得到一个 unicode 解码的 json,其中 u'חיפה' 表示为例如: 你'\u05d7\u05d9\u05e4\u05d4'
大多数脚本和应用程序在读取 Unicode 字符串时没有任何问题,但我的用户有一个!,并且由于为开源项目做出贡献,他们需要直接编辑 JSON,他们无法弄清楚希伯来语文本。
所以,问题是:我应该如何编写 json,同时在另一个编辑器中打开它会显示希伯来语字符?
我不确定这是否可以解决,因为我怀疑 JSON 一直都是 unicode,我不能在其中使用 asccii,但我不确定。
感谢帮助
最佳答案
使用 ensure_ascii=False
参数。
>>> import json
>>> city = u'חיפה'
>>> print(json.dumps(city))
"\u05d7\u05d9\u05e4\u05d4"
>>> print(json.dumps(city, ensure_ascii=False))
"חיפה"
If ensure_ascii is True (the default), all non-ASCII characters in the output are escaped with \uXXXX sequences, and the result is a str instance consisting of ASCII characters only. If ensure_ascii is False, some chunks written to fp may be unicode instances. This usually happens because the input contains unicode strings or the encoding parameter is used. Unless fp.write() explicitly understands unicode (as in codecs.getwriter()) this is likely to cause an error.
您的代码应如下所示:
import json
j = {'results': [u'חיפה']}
to_save = json.dumps(j, ensure_ascii=False)
with open('test.json', 'wb') as f:
f.write(to_save.encode('utf-8'))
或
import codecs
import json
j = {'results': [u'חיפה']}
to_save = json.dumps(j, ensure_ascii=False)
with codecs.open('test.json', 'wb', encoding='utf-8') as f:
f.write(to_save)
或
import codecs
import json
j = {'results': [u'חיפה']}
with codecs.open('test.json', 'wb', encoding='utf-8') as f:
json.dump(j, f, ensure_ascii=False)
关于python - 序列化为保留希伯来字符的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18480959/