打印python JSON回到python

时间:2013-06-03 22:09:17

标签: python json

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

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

而不是有效的JSON:

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

由于JSON无效,json.loads()自然无法解析它。

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

2 个答案:

答案 0 :(得分: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'}

答案 1 :(得分: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.