python - 当存在 unicode 数据时,Json 解码器不一致

标签 python unicode

(此问题与 this one 相关)

看一下以下 session :

Python 2.7.3 (default, Jan  2 2013, 16:53:07) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> import simplejson as json
>>> 
>>> my_json = '''[
...   {
...     "id" : "normal",
...     "txt" : "This is a normal entry"
...   },
...   {
...     "id" : "αβγδ",
...     "txt" : "This is a unicode entry"
...   }
... ]'''
>>> 
>>> cache = json.loads(my_json, encoding='utf-8')
>>> 
>>> cache
[{'txt': 'This is a normal entry', 'id': 'normal'}, {'txt': 'This is a unicode entry', 'id': u'\u03b1\u03b2\u03b3\u03b4'}]

为什么 json 解码器有时生成 unicode,有时生成纯字符串?它不是应该生成 始终 unicode 吗?

最佳答案

似乎是simplejson中的优化,来自simplejson docs :

If s is a str then decoded JSON strings that contain only ASCII characters may be parsed as str for performance and memory reasons. If your code expects only unicode the appropriate solution is decode s to unicode prior to calling decode.

注意: ASCII 中包含的任何字符在 UTF-8 和 ASCII 中的编码都是相同的。所以 ASCII 是 UTF-8 的子集。

关于python - 当存在 unicode 数据时,Json 解码器不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19701806/

相关文章:

r - 如何在 R 中设置 unicode 语言环境?

python - 将列移动为 pandas 数据框中的数据

python - 转换为二进制有什么问题?

python - 计算某些文本中多字子串的出现次数

python - 如何在 Windows 的控制台中显示语言的本地口音?

c++ - 如何使用 C++ 计算文本中 Unicode 字符的数量

python - 超参调参时简单参数是否也会改变

python - If、Elif、大于、小于逻辑

Python DELETE 字符(Unicode 7F)似乎没有做任何事情。它不应该删除后续字符,还是我做错了?

unicode - 许多unicode字符的包?