Python:json.loads在转义时阻塞 [英] Python: json.loads chokes on escapes

查看:261
本文介绍了Python:json.loads在转义时阻塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将JSON对象(用Prototype格式化)发送到ASP服务器的应用程序。在服务器上,Python 2.6 json模块尝试将JSON加载(),但由于反斜杠的某种组合而令人窒息。观察:

I have an application that is sending a JSON object (formatted with Prototype) to an ASP server. On the server, the Python 2.6 "json" module tries to loads() the JSON, but it's choking on some combination of backslashes. Observe:

>>> 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 ,因此我只是将斜杠加倍。但这显然是不好的。有人可以协助吗?作为最后的选择,我正在考虑将\转换为/,然后再次返回,但这对我来说似乎是一个真正的技巧。

So column 58 is the escaped-backslash. I thought this WAS properly escaped! UNC is \\host\dir\file.exe, so I just doubled up on slashes. But apparently this is no good. Can someone assist? As a last resort I'm considering converting the \ to / and then back again, but this seems like a real hack to me.

在此先感谢!!

推荐答案

正确的json是:

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

请注意字母 r 您也需要对 \ 进行Python转换。

Note the letter r if you omit it you need to escape \ for Python too.

>>> 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默认为对象 obj

Python REPL prints by default the repr(obj) for an object obj:

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

因此,您原来的 s 字符串未正确转义为JSON。它包含未转义的'\d''\f' print s 必须显示'\\d',否则它不是正确的JSON。

Therefore your original s string is not properly escaped for JSON. It contains unescaped '\d' and '\f'. print s must show '\\d' otherwise it is not correct JSON.

注意:JSON字符串是零个或多个Unicode字符的集合,使用反斜杠转义符将其括在双引号中( json.org )。在上述示例中,我跳过了编码问题(即从字节字符串到unicode的转换,反之亦然)。

NOTE: JSON string is a collection of zero or more Unicode characters, wrapped in double quotes, using backslash escapes (json.org). I've skipped encoding issues (namely, transformation from byte strings to unicode and vice versa) in the above examples.

这篇关于Python:json.loads在转义时阻塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆