Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I include a YAML file inside another?

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?

like image 349
kch Avatar asked Feb 09 '09 14:02

kch


People also ask

Can I include a YAML file inside another?

No, YAML does not include any kind of "import" or "include" statement. You could create a ! include <filename> handler.

How do I merge YAML files?

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.

What is multi document YAML?

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.


2 Answers

No, YAML does not include any kind of "import" or "include" statement.

like image 185
jameshfisher Avatar answered Sep 21 '22 14:09

jameshfisher


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.

Class-Based Solution

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]]} 
like image 22
Josh Bode Avatar answered Sep 19 '22 14:09

Josh Bode