simplejson.loads() 获取无效的 \escape: 'x
我正在学习如何使用simplejson来解码JSON文件。但是我遇到了“无效的\转义”错误。
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解析器应该能识别转义字符。所以我想知道哪里出了问题,以及我该怎么做。
3 个回答
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)
5
这是解析器的正常表现,因为这个JSON是无效的。在字符串中,斜杠后面只能跟 "
、\
、/
、b
、f
、n
、r
、t
或 u
(后面必须跟4个十六进制字符)。而 x
是不被允许的。具体可以查看这个规范:http://json.org/
15
JSON格式没有像某些语言(包括JavaScript)那样的十六进制转义符(\xNN
),详细信息可以查看这里。它有一种unicode转义符,格式是\uNNNN
,其中NNNN
是四个十六进制数字,但没有\x
这种十六进制转义符。