TOC

Python 2.7 Json 字符串类型的问题

今日发现一个 Python 2.7 的一个大坑:部分版本下 JSON 解析字符串为 str 类型,部分版本解析成 unicode 类型。

Python 2.7 (r27:82500, Apr 12 2016, 21:09:36)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-16)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import json; print(repr(json.loads('"a"')));
'a'

Python 2.7.15 (default, Jul 22 2019, 17:38:55)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import json; json.loads('"s"'); exit();
's'

Python 2.7.15 (default, Jun 26 2018, 11:17:18)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import json; json.loads('"s"'); exit();
u's'

Python 2.7.18 (default, Mar 23 2022, 15:07:54)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import json; json.loads('"s"'); exit();
u's'

找到一个相关的 Issue:json.loads() on str should return unicode, not str
对应 GitHub 上的 Issue#54247

根据相关内容,这个问题影响了 Python 2.7 的一些版本。


还有:json.loads() returns str instead of unicode for empty strings
对应 GitHub 上的 Issue#56191