python yaml 加载格式化字符串

python yaml load formatted string

我正在尝试加载包含 python 格式字符串的 yaml,例如test: {formatted_string}。这将允许我使用 dictionary["test"].format(formatted_string="hello yaml") 格式化字符串,但是当我加载 yaml 时,它会自动转换为 {'test': {'formatted_string': None}} 而不是 {'test': '{formatted_string}'}.

已经有数十个 .yaml 文件以这种方式格式化。

我在 pyyaml 文档或 SO 上的任何地方都没有看到这个。

为清楚起见,完整的代码:

import yaml


data = """
test: {formatted_string}
"""
d1 = yaml.load(data)
print(d1)
# {'test': {'formatted_string': None}}

d2 = {"test": "{formatted_string}"}
print(d2)
# {'test': '{formatted_string}'}

d2["test"] = d2["test"].format(formatted_string="hello yaml")
print(d2)
# {'test': 'hello yaml'}

谢谢!

YAML 中的 { 字符(如 JSON)引入字典。就是这样:

a_dictionary:
  key1: value1
  key2: value2

完全等同于:

a_dictionary: {key1: value1, key2: value2}

所以当你写...

test: {formatted_string}

...YAML 解析器的东西你正在引入一个字典,它有一个键(formatted_string)并且没有值。如果你想使用 { 作为 YAML value 的一部分,你需要引用它:

test: "{formatted_string}"

比较:

>>> yaml.safe_load('test: {formatted_string}')
{'test': {'formatted_string': None}}
>>> yaml.safe_load('test: "{formatted_string}"')
{'test': '{formatted_string}'}

一般来说,如果你总是引用你的 YAML 字符串,你的生活会更轻松 :)。