【问题标题】:Processing Unicode strings in returned JSON data处理返回的 JSON 数据中的 Unicode 字符串
【发布时间】:2013-01-17 06:06:31
【问题描述】:

我正在尝试从获取的 JSON 中打印数据,但是该数据具有 unicode 解码的数据。如何对其进行编码(参见示例)以正确显示。我对 python 很陌生,无法让它工作,我在命令行终端上使用 Windows 7、python 2.7。谢谢!

示例:结果>>标题:

'R\u00f6yksopp - 49 Percent' 必须将其打印为 'Röyksopp - 49 Percent'

"title": "R\u00f6yksopp - 49 Percent",

JSON:

"results": [{
        "style": ["House", "Electro", "Synth-pop"],
        "thumb": "http://api.discogs.com/image/R-90-530519-1236701656.jpeg",
        "format": ["CD", "Maxi-Single"],
        "country": "Europe",
        "barcode": ["5 028589 023420", "BEL/BIEM", "LC 3098"],
        "uri": "/R%C3%B6yksopp-49-Percent/master/30161",
        "label": ["Virgin", "Labels", "Wall Of Sound"],
        "catno": "0946 3378752 0",
        "year": "2005",
        "genre": ["Electronic"],
        "title": "R\u00f6yksopp - 49 Percent",
        "resource_url": "http://api.discogs.com/masters/30161",
        "type": "master",
        "id": 30161
    }

【问题讨论】:

  • \u00f6ö。命令提示符是否支持这些字符?
  • 你使用库来解析 json 吗? (你是“导入 json”还是“导入 cjson”?)
  • 显示你使用的实际 Python 代码,以及你得到的输出。
  • #!/usr/bin/env python # -*- coding: utf-8 -*- import json d = json.loads(u'''{"title": "R\u00f6yksopp - 49 Percent"}''') print d['title'].encode('utf-8')
  • 以上代码打印不正确..

标签: python json unicode


【解决方案1】:

环境:Windows 7,默认代码页 = 850,Python 2.7.3

使用您输入的缩减版:

>>> import json
>>> js = """{
...         "style": ["House", "Electro", "Synth-pop"],
...         "title": "R\u00f6yksopp - 49 Percent",
...         "id": 30161
...     }"""
>>>
>>> j = json.loads(js)
>>> j
{u'style': [u'House', u'Electro', u'Synth-pop'], u'id': 30161, u'title': u'R\xf6yksopp - 49 Percent'}
>>> j['title']
u'R\xf6yksopp - 49 Percent'
>>> print j['title']
Röyksopp - 49 Percent
>>>

【讨论】:

  • 感谢您的回复,但不幸的是,我的 unicode 字符串因请求而异,例如,下面提到的代码不会在我的终端上输出,但您发布的上述代码仅适用于列出的符号。 .我正在寻找任何 unicode 字符的通用解决方案...

  • #!/usr/bin/env python # -*- coding: utf-8 -*- import json js = """{"style": ["House", "Electro", "Synth-pop"],"title": "Gigi D\u2010Agostino - The Riddle","id": 30161}""" j = json.loads(js) print j['title'] - 这里 u\2010 是一个连字符(我认为)不会显示...我将粘贴下面的终端错误..
  • print j['title'] File "C:\Python27\lib\encodings\cp437.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeEncodeError: 'charmap' codec can't encode character u'\u2010' in position 1: character maps to <undefined>
  • Windows 命令行没有好的通用解决方案。试试 IDLE。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-01
  • 1970-01-01
  • 2019-09-04
  • 1970-01-01
  • 2011-01-10
  • 1970-01-01
相关资源
最近更新 更多