我遇到了一种情况,需要将可由用户编辑的 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 文档?
- 如何将该字符串加载到将返回准确值的字典中?
最佳答案
您遇到了字符串文字支持的转义序列。使用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
关于python - 将 UNC 存储在 JSON 中并加载到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19255570/