six.u()不跳过HTML字符串

2024-04-24 07:27:04 发布

您现在位置:Python中文网/ 问答频道 /正文

使用Python2.7。作为JSON响应的一部分,API返回以下字符串:

<a href="https://about.twitter.com/products/tweetdeck" rel="nofollow">TweetDeck</a>

我使用的库内部有:

^{pr2}$

json.dumps()输出是:

^{3}$

可以使用json.loads正确解码此输出

但是对six.u的调用给出了:

u'"<a href="https://about.twitter.com/products/tweetdeck" rel="nofollow">TweetDeck</a>"'

尝试用json.loads解码这个字符串会抛出一个错误。在

ValueError: Extra data: line 1 column 11 - line 1 column 86 (char 10 - 85)

six.u的调用似乎转义了href值,但我不完全确定如何修复此问题。在


Tags: 字符串httpscomjsontwitter解码productsrel
1条回答
网友
1楼 · 发布于 2024-04-24 07:27:04

six.u()用于unicode字符串文本,而不是JSON输出。不应使用它将JSON解码为Unicode字符串。在

^{} documenation

A “fake” unicode literal. text should always be a normal string literal. In Python 2, u() returns unicode, and in Python 3, a string. Also, in Python 2, the string is decoded with the unicode-escape codec, which allows unicode escapes to be used in it.

强调我的。在

相反,如果使用Python 2,则对字符串进行解码:

json_string = json.dumps(s)
if hasattr(json_string, 'decode'):
    # Python 2; decode to a Unicode value
    json_string = json_string.decode('ascii')

或者使用unicode()函数并捕获Python 3中的NameError

^{pr2}$

或者在调用json.dumps()时将ensure_ascii设置为False

json_string = json.dumps(s, ensure_ascii=False)

{{8}仍然可以安全地返回cd9}中的值,但只有在cd9}中才能安全地返回值。在

无论哪种方式,您都可以在python2和python3之间获得一致的值;six.u()decode还将\uhhhhJSONUnicode转义序列解码为Unicode代码点,而python3json的结果将保持这些代码点不变。通过解码,您可以在python2和python3中保留\uhhhh序列,而使用ensure_ascii可以在这两种代码中获得Unicode代码点。在

因为这是一个第三方库,所以您不能真正从这个错误中恢复过来;您不能在前面插入多余的反斜杠,然后再将其删除,因为您无法将这些反斜杠与普通反斜杠区分开。在

相关问题 更多 >