【发布时间】:2016-08-18 09:01:13
【问题描述】:
我刚刚开始使用 YAML 和 Python,我正在尝试在 Python 中解析包含锚点和别名的 YAML。
在这个 YAML 中,我覆盖了锚点以使某些节点具有不同的值。
我的 YAML 示例:
Some Colors: &some_colors
color_primary: &color_primary "#112233FF"
color_secondary: &color_secondary "#445566FF"
Element: &element
color: *color_primary
Overwrite some colors: &overwrite_colors
color_primary: &color_primary "#000000FF"
Another element: &another_element
color: *color_primary
具有(JSON 格式)的预期结果:
{
"Some Colors": {
"color_primary": "#112233FF",
"color_secondary": "#445566FF"
},
"Element": {
"color": "#112233FF"
},
"Overwrite some colors": {
"color_primary": "#000000FF"
},
"Another element": {
"color": "#000000FF"
}
}
我测试了上面的 YAML sn-p here
根据我在 YAML 文档中阅读的内容;这应该从 1.1 版开始(我认为),但至少 YAML 1.2 版应该支持它。
但每当我尝试使用 PyYAML(使用 yaml.load())或 ruamel,yaml 包(使用 ruamel.yaml.load())解析 YAML 时,我都会收到“重复锚点”错误。
我在这里做错了什么?以及如何解决这个问题?
编辑:
在ruamel 的所有者的帮助下,我找到了上述问题的解决方案。
从ruamel v0.12.3 开始,上述工作按预期工作,尽管您将收到ReusedAnchorWarnings。
可以使用以下 sn-p 抑制这些警告:
import warnings
from ruamel.yaml.error import ReusedAnchorWarning
warnings.simplefilter("ignore", ReusedAnchorWarning)
在到期时给予学分;他们都去ruamel的所有者。
作为附加问题;当我将上述 YAML 修改为 时(注意 // <-- Added this 处的更改):
Some Colors: &some_colors
color_primary: &color_primary "#112233FF"
color_secondary: &color_secondary "#445566FF"
Element: &element
color: *color_primary
Overwrite some colors: &overwrite_colors
<<: *some_colors // <-- Added this to include 'color_secondary' as well
color_primary: &color_primary "#000000FF"
Another element: &another_element
color: *color_primary
输出是:
{
"Some Colors": {
"color_primary": "#000000FF",
"color_secondary": "#445566FF"
},
"Element": {
"color": "#112233FF"
},
"Overwrite some colors": {
"color_primary": "#000000FF",
"color_secondary": "#445566FF"
},
"Another element": {
"color": "#445566FF" // <-- Now the value is 'color_secondary' instead of 'color_primary'?
}
}
为什么Another element 的color 会查看color_secondary 的值?
还有什么办法可以解决这个问题吗?
【问题讨论】: