1

我有一种情况,需要将用户可编辑的 JSON 配置文档加载到我的应用程序的字典中。

导致问题的一种特定情况是 Windows UNC 路径,例如:

\\server\share\file_path

因此,有效的 JSON 直观地是:

{"foo" : "\\\server\\share\\file_path"}

但是这是无效的。

我要绕着这个圈子。以下是一些试验:

# starting with a json string
>>> x = '{"foo" : "\\\server\\share\\file_path"}'
>>> json.loads(x)
ValueError: Invalid \escape: line 1 column 18 (char 18)

# that didn't work, let's try to reverse engineer a dict that's correct
>>> d = {"foo":"\\server\share\file_path"}
>>> d["foo"]
'\\server\\share\x0cile_path'

# good grief, where'd my "f" go?

概括

  • 如何创建包含\\server\share\file_path的格式正确的 JSON 文档?
  • 如何将该字符串加载到将返回确切值的字典中?
4

1 回答 1

1

您遇到了字符串文字支持的转义序列。使用raw strings,这变得更加清晰:

>>> d = {"foo":"\\server\share\file_path"}
>>> d
{'foo': '\\server\\share\x0cile_path'}
>>> d = {"foo": r"\\server\share\file_path"}
>>> d
{'foo': '\\\\server\\share\\file_path'}
>>> import json
>>> json.dumps(d)
'{"foo": "\\\\\\\\server\\\\share\\\\file_path"}'
>>> with open('out.json', 'w') as f: f.write(json.dumps(d))
... 
>>> 
$ cat out.json 
{"foo": "\\\\server\\share\\file_path"}

没有原始字符串,你必须“逃避所有的事情!”

>>> d = {"foo":"\\server\share\file_path"}
>>> d
{'foo': '\\server\\share\x0cile_path'}
>>> d = {"foo":"\\\\server\\share\\file_path"}
>>> d
{'foo': '\\\\server\\share\\file_path'}
>>> print d['foo']
\\server\share\file_path
于 2013-10-08T18:37:54.890 回答