python - 序列化为保留希伯来字符的 JSON

标签 python json python-2.7 unicode

我有以下用例:

我从数据中生成一个带有数据的 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))
"חיפה"

根据 json.dump documentation :

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/

相关文章:

python - Airflow:如何确保 DAG 每 5 分钟运行一次?

python - 如何在数组python中获取一个数字的特定时间

c# - JSON反序列化可变数量的属性

php - MySQL 到嵌套 JSON

json - 在 Go 中,为什么 JSON null 有时不会传递给 UnmarshalJSON 进行解码?

python - python中深度图的表面法线计算

python - 尝试在 python 中执行 get 请求时出现 [Errno 110] 'Connection timed out'

python - 运行时更新 scrapy 蜘蛛

c++ - 从 Eclipse 调试 Python C++ 扩展(在 Linux 下)

python - 在 pySpark 数据帧图中设置 x 和 y 索引