2

所以,我有人向我发送了一些数据的 JSON 转储,但他们显然是在 python 中懒惰地(通过打印)所以(简化的)数据是:

{u'x': u'somevalue', u'y': u'someothervalue'}

而不是有效的 JSON:

{"x": "somevalue", "y": "someothervalue"}

由于它不是有效的 JSON,因此 json.loads() 自然无法解析它。

Python 是否包含任何模块来解析它自己的输出?我实际上认为自己解析它可能比试图向这个人解释他做错了什么以及如何解决它更快。

4

2 回答 2

4

您可能能够摆脱以下情况:

>>> s = "{u'x': u'somevalue', u'y': u'someothervalue'}"
>>> from ast import literal_eval
>>> literal_eval(s)
{u'y': u'someothervalue', u'x': u'somevalue'}
于 2013-06-03T22:12:34.917 回答
1

demjson python模块允许严格和非严格操作。以下是非严格模式下的一些津贴列表:

在 NON-STRICT 模式下处理时允许执行以下操作:

* Unicode format control characters are allowed anywhere in the input.
* All Unicode line terminator characters are recognized.
* All Unicode white space characters are recognized.
* The 'undefined' keyword is recognized.
* Hexadecimal number literals are recognized (e.g., 0xA6, 0177).
* String literals may use either single or double quote marks.
* Strings may contain \x (hexadecimal) escape sequences, as well as the
  \v and \0 escape sequences.
* Lists may have omitted (elided) elements, e.g., [,,,,,], with
  missing elements interpreted as 'undefined' values.
* Object properties (dictionary keys) can be of any of the
  types: string literals, numbers, or identifiers (the later of
  which are treated as if they are string literals)---as permitted
  by ECMAScript.  JSON only permits strings literals as keys.
于 2013-06-03T22:16:19.947 回答