gpt4 book ai didi

python - 为什么 json.loads 返回一个 unicode 对象而不是字符串

转载 作者:太空狗 更新时间:2023-10-30 02:29:57 25 4
gpt4 key购买 nike

我无法理解为什么以下类型从 str 更改为 unicode。

案例1

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']}

案例2

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 中,我们看到的是 unicode 对象,而在案例 1 中,我们看到的是字符串。我没有看到两个版本的 python 中发生了任何可能导致此问题的代码更改。可能是我错过了什么。任何线索将不胜感激。谢谢

最佳答案

Python 2.7 版有一个错误导致您的第一个示例中的行为。这已在 2.7.5 中修复。参见 issue 10038 .请注意,版本 2.6.6 的行为类似于 2.7.5,表明 2.7 的行为是对先前建立的行为的更改。

I don't think that any code change has happened in the two version of python that can lead to this.

当您可以检查并确定时,无需“认为”什么都没有改变! Python 的每个版本都带有详尽的注释,准确说明发生了什么变化。术语“json”在 Python 2.7.5 中出现了二十八次 change log .当然,也可以在 Python 2.7.1、2.7.2、2.7.3 和 2.7.4 中对 JSON 进行更改。

关于python - 为什么 json.loads 返回一个 unicode 对象而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29928168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com