2013-06-03 249 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列出的特定用例,我認爲你的答案是一個更好的解決方案:) –