2009-10-01 134 views
11

我有一個應用程序發送JSON對象(使用Prototype格式)到ASP服務器。在服務器上,Python 2.6的「json」模塊嘗試加載()JSON,但它在某些反斜槓組合上窒息。觀察:Python:json.loads逃生甩

>>> s 
'{"FileExists": true, "Version": "4.3.2.1", "Path": "\\\\host\\dir\\file.exe"}' 

>>> tmp = json.loads(s) 
Traceback (most recent call last): 
    File "<interactive input>", line 1, in <module> 
    {... blah blah blah...} 
    File "C:\Python26\lib\json\decoder.py", line 155, in JSONString 
    return scanstring(match.string, match.end(), encoding, strict) 
    ValueError: Invalid \escape: line 1 column 58 (char 58) 

>>> s[55:60] 
u'ost\\d' 

所以列58是轉義反斜槓。我認爲這是適當逃脫! UNC是\\host\dir\file.exe,所以我只是斜槓加倍。但顯然這不是好事。有人可以協助嗎?作爲最後的手段,我正在考慮將\轉換爲/然後再轉回來,但這對我來說似乎是一個真正的黑客。

在此先感謝!

回答

16

正確的JSON是:

r'{"FileExists": true, "Version": "4.3.2.1", "Path": "\\\\host\\dir\\file.exe"}' 

注意字母r如果你忽略它,你需要逃避\爲Python了。

>>> import json 
>>> d = json.loads(s) 
>>> d.keys() 
[u'FileExists', u'Path', u'Version'] 
>>> d.values() 
[True, u'\\\\host\\dir\\file.exe', u'4.3.2.1'] 

注意區別:

>>> repr(d[u'Path']) 
"u'\\\\\\\\host\\\\dir\\\\file.exe'" 
>>> str(d[u'Path']) 
'\\\\host\\dir\\file.exe' 
>>> print d[u'Path'] 
\\host\dir\file.exe 

的Python REPL打印默認repr(obj)爲對象obj

>>> class A: 
... __str__ = lambda self: "str" 
... __repr__ = lambda self: "repr" 
... 
>>> A() 
repr 
>>> print A() 
str 

因此你原來s字符串不正確轉義的JSON。它包含未轉義的'\d''\f'print s必須顯示'\\d'否則它是不正確的JSON。

注:JSON字符串是零個或多個Unicode字符的集合,用雙引號括起來,使用反斜槓轉義字符(json.org)。在上面的例子中,我跳過了編碼問題(即從字節串到Unicode的轉換,反之亦然)。

+0

:) >>> S = R'{ 「FILEEXISTS」:真,「Version」:「4.3.2.1」,「Path」:「\\\\ host \\ dir \\ file.exe」}' >>> json.loads(s) {u'FileExists' :True,u'Path':u'\\\\ host \\ dir \\ file.exe',u'Version':u'4.3.2.1'} – Chris 2009-10-01 18:01:50

+0

那麼r實際上在做什麼?我如何將它應用於已存儲爲「foo」的字符串。它是一種編碼? – Chris 2009-10-01 18:03:36

+0

's =''打破格式。 – jfs 2009-10-01 18:04:48

1
>>> s 
'{"FileExists": true, "Version": "4.3.2.1", "Path": "\\\\host\\dir\\file.exe"}' 
>>> print s 
{"FileExists": true, "Version": "4.3.2.1", "Path": "\\host\dir\file.exe"} 

你沒有真正逃脫字符串,因此它試圖解析像\d\f無效的轉義碼。考慮使用經過良好測試的JSON編碼器,如json2.js

2

由於異常給你違規轉義字符的索引,我開發這個小黑客可能是好的:)

def fix_JSON(json_message=None): 
    result = None 
    try:   
     result = json.loads(json_message) 
    except Exception as e:  
     # Find the offending character index: 
     idx_to_replace = int(e.message.split(' ')[-1].replace(')',''))  
     # Remove the offending character: 
     json_message = list(json_message) 
     json_message[idx_to_replace] = ' ' 
     new_message = ''.join(json_message)  
     return fix_JSON(json_message=new_message) 
    return result 
+1

感謝您的代碼。在我的情況下(Python 3.5),需要將idx_to_replace = int(e.message.split('')[ - 1] .replace(')',''))'改爲'idx_to_replace = int(str e).split('')[ - 1] .replace(')',''))' – TitanFighter 2016-09-25 19:49:47