2015-04-28 76 views
4

我不明白为什么以下类型从str改为unicode。为什么json.loads返回一个unicode对象而不是字符串

CASE1

Python 2.7 (r27:82500, Nov 19 2014, 18:07:42) 
[GCC 4.5.1 20100924 (Red Hat 4.5.1-4)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import json 
>>> x = {'resources': {}, 'tags': ['a', 'b']} 
>>> ret = json.dumps(x) 
>>> ret 
'{"resources": {}, "tags": ["a", "b"]}' 
>>> 
>>> type(ret) 
<type 'str'> 
>>> ret2 = json.loads(ret) 
>>> ret2 
{'resources': {}, 'tags': ['a', 'b']} 

CASE2

Python 2.7.5 (default, Apr 22 2015, 21:27:15) 
[GCC 4.9.2 20141101 (Red Hat 4.9.2-1)] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import json 
>>> x = {'resources': {}, 'tags': ['a', 'b']} 
>>> ret = json.dumps(x) 
>>> ret 
'{"resources": {}, "tags": ["a", "b"]}' 
>>> type(x) 
<type 'dict'> 
>>> type(ret) 
<type 'str'> 
>>> ret2 = json.loads(ret) 
>>> ret2 
{u'resources': {}, u'tags': [u'a', u'b']} 
>>> 

因此,在2的情况下,我们看到在1的情况下,我们看到的字符串,而不是Unicode对象。 我看不到任何代码更改发生在可导致此问题的两个版本的python中。可能是我错过了一些东西。 任何线索将不胜感激。 谢谢

回答

6

Python 2.7版有一个错误,导致您的第一个示例中的行为。这在2.7.5中得到了修正。见issue 10038。请注意,版本2.6.6的行为与2.7.5相同,表明2.7行为与以前建立的行为相比有所改变。

我不认为任何代码的变化发生在两个版本的python可以导致这种情况。

当您可以检查并确定时,无需“思考”任何改变!每一个Python发行版都附有大量的注释,指明确切的变化。术语“json”在Python 2.7.5 change log中出现了二十八次。当然,也可以在Python 2.7.1,2.7.2,2.7.3和2.7.4中对JSON进行更改。

+0

其实,我的意思是,在json.loads()函数定义中没有看到任何相关的代码更改。可能是我错过了一些东西。 – user3872776

相关问题