【问题标题】:Unicode decoding error from json webpage来自json网页的Unicode解码错误
【发布时间】:2014-07-22 00:03:00
【问题描述】:

按照事情的方式,我在 python 中解码一些 unicode 时遇到问题

具体来说,这个网页:xkcd.com/403/info.0.json

相关部分为Paul Erd\u00c5\u0091s!

当我通过 json 解码器运行它时,unicode 被解码,但没有使用正确的编解码器

我目前正在使用单线:

requests.get("http://xkcd.com/403/info.0.json").json()["alt"][-12:]

得到'Paul ErdÅ\x91s!' 这显然不是我想要的

关于我可以做些什么来解决它的任何想法?

【问题讨论】:

    标签: python json unicode python-requests python-3.4


    【解决方案1】:

    要修复该 JSON,您需要先编码为 Latin-1(因为它会天真地转码字节),然后从 UTF-8 解码。

    两次。因为它是双断的。

    >>> json.loads('"Erd\u00c3\u0085\u00c2\u0091s!"')
    u'Erd\xc3\x85\xc2\x91s!'
    >>> json.loads('"Erd\u00c3\u0085\u00c2\u0091s!"').encode('latin-1').decode('utf-8')
    u'Erd\xc5\x91s!'
    >>> json.loads('"Erd\u00c3\u0085\u00c2\u0091s!"').encode('latin-1').decode('utf-8').encode('latin-1').decode('utf-8')
    u'Erd\u0151s!'
    >>> print json.loads('"Erd\u00c3\u0085\u00c2\u0091s!"').encode('latin-1').decode('utf-8').encode('latin-1').decode('utf-8')
    Erdős!
    

    【讨论】:

    • wait, "UnicodeEncodeError: 'latin-1' codec can't encode character '\u0151' in position 102: ordinal not in range(256)" 第二次解码。有什么想法吗?
    • 哦,我明白了,这是因为它与替代文本的成绩单不同(!)...... -_-
    猜你喜欢
    • 1970-01-01
    • 2017-01-17
    • 2021-09-01
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    相关资源
    最近更新 更多