因此,我有两个YAML文件,"A“和" B”,我希望将A的内容插入到B中,要么像数组一样拼接到现有的数据结构中,要么像某个散列键的值一样作为元素的子元素。
这到底有没有可能?多么?如果不是,有没有关于规范参考的建议?
发布于 2013-03-16 00:39:30
不,YAML不包含任何类型的"import“或" include”语句。
发布于 2012-01-24 02:45:23
据我所知,在YAML中不直接支持Include,你必须自己提供一种机制,但这通常很容易做到。
我在我的python应用程序中使用了YAML作为配置语言,在这种情况下,通常会定义如下约定:
>>> main.yml <<<
includes: [ wibble.yml, wobble.yml]
然后在我的(python)代码中,我这样做:
import yaml
cfg = yaml.load(open("main.yml"))
for inc in cfg.get("includes", []):
cfg.update(yaml.load(open(inc)))
唯一的缺点是includes中的变量将始终覆盖main中的变量,并且无法通过更改"includes:语句“在main.yml文件中的出现位置来更改优先顺序。
从另一个角度来看,YAML并不支持includes,因为它的设计并不像基于文件的标记那样专一。如果您在对AJAX请求的响应中获得了include,那么include意味着什么?
发布于 2012-09-04 01:58:44
根据@Josh_Bode的回答,下面是我自己的PyYAML解决方案,它的优点是它是yaml.Loader
的一个自包含子类。它不依赖于任何模块级全局变量,也不依赖于修改yaml
模块的全局状态。
import yaml, os
class IncludeLoader(yaml.Loader):
"""
yaml.Loader subclass handles "!include path/to/foo.yml" directives in config
files. When constructed with a file object, the root path for includes
defaults to the directory containing the file, otherwise to the current
working directory. In either case, the root path can be overridden by the
`root` keyword argument.
When an included file F contain its own !include directive, the path is
relative to F's location.
Example:
YAML file /home/frodo/one-ring.yml:
---
Name: The One Ring
Specials:
- resize-to-wearer
Effects:
- !include path/to/invisibility.yml
YAML file /home/frodo/path/to/invisibility.yml:
---
Name: invisibility
Message: Suddenly you disappear!
Loading:
data = IncludeLoader(open('/home/frodo/one-ring.yml', 'r')).get_data()
Result:
{'Effects': [{'Message': 'Suddenly you disappear!', 'Name':
'invisibility'}], 'Name': 'The One Ring', 'Specials':
['resize-to-wearer']}
"""
def __init__(self, *args, **kwargs):
super(IncludeLoader, self).__init__(*args, **kwargs)
self.add_constructor('!include', self._include)
if 'root' in kwargs:
self.root = kwargs['root']
elif isinstance(self.stream, file):
self.root = os.path.dirname(self.stream.name)
else:
self.root = os.path.curdir
def _include(self, loader, node):
oldRoot = self.root
filename = os.path.join(self.root, loader.construct_scalar(node))
self.root = os.path.dirname(filename)
data = yaml.load(open(filename, 'r'))
self.root = oldRoot
return data
https://stackoverflow.com/questions/528281
复制相似问题