python - 将 UNC 存储在 JSON 中并加载到字典中

标签 python json

我遇到了一种情况,需要将可由用户编辑的 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/

相关文章:

python - PyQt5 自定义标签中不出现滚动条

javascript - Angular 根据另一个 json 文件从一个 json 文件读取数据

ios - 序列化 NSDictionary 时出错

java - 空 JSON 与 null 转换为

python - 如何让物体永远在同一高度弹跳

Python:限制用于发布到服务器的 json 字符串的大小

python - 为什么使用 virtualenv 时 Python 构建突然不是 Framework 构建?

python - 安装 Pyspark 时遇到问题

java - 如何从 Json 转换为 Protobuf?

json - 具有 (RegEx) 模式的 json-schema 中的枚举