【问题标题】:Parsing JSON with Python用 Python 解析 JSON
【发布时间】:2010-07-01 07:19:26
【问题描述】:

在 Python 中解析 JSON 响应时出现错误。例如:

{
    "oneliners": [
        "she\'s the one",
        "who opened the gates"
    ]
}

JSON 解码器会在单引号上出现无效转义。通常人们会在解码可能包含无效转义的响应之前应用正则表达式来删除转义斜杠字符吗?

【问题讨论】:

  • 你用的是什么 JSON 解码器?
  • @sdolan: 任何 strict JSON 解码器(例如simplejson - pypi.python.org/pypi/simplejson)都会因此而窒息,这确实是 JSON 中的无效转义(与 JavaScript 不同) :json.org
  • @T.J Crowder:感谢您的澄清。

标签: python json


【解决方案1】:

Pyparsing 附带一个 JSON 解析示例(或者您可以在线获取它here):

>>> text = r"""{
...     "oneliners": [
...         "she\'s the one",
...         "who opened the gates"
...     ]
... } """
>>> text
'{       \n    "oneliners": [       \n        "she\\\'s the one",       \n        "who opened the gates"       \n    ]       \n} '
>>> obj = jsonObject.parseString(text)
>>> obj.asList()
[['oneliners', ["she\\'s the one", 'who opened the gates']]]
>>> obj.asDict()
{'oneliners': (["she\\'s the one", 'who opened the gates'], {})}
>>> obj.oneliners
(["she\\'s the one", 'who opened the gates'], {})
>>> obj.oneliners.asList()
["she\\'s the one", 'who opened the gates']

不要被obj.oneliners 中看似包含的dict('{}')所推迟,这只是pyparsing ParseResults 对象的repr 输出。您可以将 obj.oneliners 视为普通列表 - 或者,如果您愿意,可以使用 asList 将其内容提取为列表,如图所示。

【讨论】:

    【解决方案2】:

    如果你的 JSON 字符串表示中有 \' 字符序列,并且你知道它应该是 ',这意味着它之前被不正确地转义,你应该在那里解决问题。

    如果不能,则应在向 JSON 解析器提供此类字符串之前进行替换。 simplejson 将无法解析它,cjsonanyjson 不会失败,但会按字面意思处理它,因此您将在结果数据中包含反斜杠撇号序列。

    【讨论】:

      【解决方案3】:
      import json
      s = """{
       "oneliners": [
       "she\'s the one",
       "who opened the gates"
       ]
      }"""
      
      print "%r" % json.loads(s)
      

      这似乎工作得很好,无论如何在 Python 2.6 及更高版本中。

      【讨论】:

      • 必须使用原始字符串定义 s,否则 json.loads 将永远看不到那个 '\'。 (而且我不是反对你的人。)
      • 可以发誓我尝试了原始版本的字符串,对不起,第一篇文章太糟糕了。
      猜你喜欢
      • 2019-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      相关资源
      最近更新 更多