2010-11-28 25 views
5

我正在學習如何使用simplejson解碼JSON文件。但我遭受了「無效\逃脫」錯誤。 下面是代碼simplejson.loads()得到無效轉義:'x'

import simplejson as json 

def main(): 
    json.loads(r'{"test":"\x27"}') 

if __name__ == '__main__': 
    main() 

這裏是錯誤消息

Traceback (most recent call last): 
    File "hello_world.py", line 7, in <module> 
    main() 
    File "hello_world.py", line 4, in main 
    json.loads(r'{"test":"\x27"}') 
    File "C:\Users\zhangkai\python\simplejson\__init__.py", line 307, in loads 
    return _default_decoder.decode(s) 
    File "C:\Users\zhangkai\python\simplejson\decoder.py", line 335, in decode 
    obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 
    File "C:\Users\zhangkai\python\simplejson\decoder.py", line 351, in raw_decode 

    obj, end = self.scan_once(s, idx) 
    File "C:\Users\zhangkai\python\simplejson\scanner.py", line 36, in _scan_once 
    return parse_object((string, idx + 1), encoding, strict, _scan_once, object_ 
hook) 
    File "C:\Users\zhangkai\python\simplejson\decoder.py", line 185, in JSONObject 

    value, end = scan_once(s, end) 
    File "C:\Users\zhangkai\python\simplejson\scanner.py", line 34, in _scan_once 
    return parse_string(string, idx + 1, encoding, strict) 
    File "C:\Users\zhangkai\python\simplejson\decoder.py", line 114, in py_scanstr 
ing 
    raise ValueError(errmsg(msg, s, end)) 
ValueError: Invalid \escape: 'x': line 1 column 10 (char 10) 

我認爲JSON解析器應該承認逃逸。所以我想知道什麼是錯的,我該怎麼做。

+2

@pyfunc謝謝,我會嘗試下一次格式化我的問題提得好。:) – kkpattern 2010-11-28 08:57:23

回答

8

與某些語言(包括JavaScript)和符號表示法一樣,JSON沒有十六進制轉義(\xNN),details here。它有一個Unicode轉義,\uNNNN其中NNNN是四個十六進制數字,但沒有\x十六進制轉義。

+0

感謝。因此,如果JSON文件具有\ x符號,我應該首先自己轉換它? – kkpattern 2010-11-28 08:55:30

2

這是來自解析器的預期行爲,因爲JSON無效;一個串內的斜線可以僅通過"\/bfnrtu(其然後必須後跟4個十六進制字符)被遵循。 x是不允許的。看到http://json.org/

0

規範嘗試python-cjson

import cjson 
s = cjson.encode({'abc':123,'def':'xyz'}) 
print 'json: %s - %s' % (type(s), s) 
s = cjson.decode(s) 
print '%s - %s' % (type(s), s)