2013-06-03 218 views
2

所以,我曾有人给我一些数据的JSON转储,但他们显然做到了懒洋洋地(通过印刷)的蟒蛇,这样(简化)的数据是:印刷蟒JSON回蟒蛇

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

,而不是有效的JSON:

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

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

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

回答

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

权。还有原始的,不安全的内置'eval()'。但不要使用'eval()',使用'ast.literal_eval()'。 http://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval – steveha

1

demjson Python模块允许严格和非严格操作。下面是一些在非严格模式下的津贴清单:

下在非严格模式处理时,被允许:

* 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. 
+0

这将是一个额外的建议,我的答案,但我不能得到它的工作 - 任何想法如果有任何争论应该用来满足OP的要求? –

+0

@Jon Clements当你初始化JSON类时,你可以通过'strict = False'来传递我在上面发布的配额列表。从阅读Josh的例子看来,他们应该允许解析内容。但是,对于Josh列出的特定用例,我认为你的答案是一个更好的解决方案:) –