So I have two YAML files, "A" and "B" and I want the contents of A to be inserted inside B, either spliced into the existing data structure, like an array, or as a child of an element, like the value for a certain hash key.
Is this possible at all? How? If not, any pointers to a normative reference?
No, YAML does not include any kind of "import" or "include" statement. You could create a ! include <filename> handler.
Yaml files can be merged using the 'merge' command. Each additional file merged with the first file will set values for any key not existing already or where the key has no value.
YAML Multi Documents YAML format allows multiple documents to be embedded in a single file. They only have to be separated with a line containing triple-dash separator ---. YAMLJSON.
No, YAML does not include any kind of "import" or "include" statement.
Your question does not ask for a Python solution, but here is one using PyYAML.
PyYAML allows you to attach custom constructors (such as !include
) to the YAML loader. I've included a root directory that can be set so that this solution supports relative and absolute file references.
Here is a class-based solution, that avoids the global root variable of my original response.
See this gist for a similar, more robust Python 3 solution that uses a metaclass to register the custom constructor.
import yaml import os class Loader(yaml.SafeLoader): def __init__(self, stream): self._root = os.path.split(stream.name)[0] super(Loader, self).__init__(stream) def include(self, node): filename = os.path.join(self._root, self.construct_scalar(node)) with open(filename, 'r') as f: return yaml.load(f, Loader) Loader.add_constructor('!include', Loader.include)
An example:
foo.yaml
a: 1 b: - 1.43 - 543.55 c: !include bar.yaml
bar.yaml
- 3.6 - [1, 2, 3]
Now the files can be loaded using:
>>> with open('foo.yaml', 'r') as f: >>> data = yaml.load(f, Loader) >>> data {'a': 1, 'b': [1.43, 543.55], 'c': [3.6, [1, 2, 3]]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With