[Solved]: How can I import an YAML file inside another YAML file?

Problem Statement:

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.

outside from YAML language some options are present. like these:

1. Class-Based Solution: PyYAML(The next generation YAML parser and emitter for Python) 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.

import yamlimport os.pathclass 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)



a: 42b:    - 12.53    - 123.64c: !include addfile.yaml


- 32- [1, 2, 3]

Now files can be loaded using:

>>> with open('example.yaml', 'r') as f:>>>    data = yaml.load(f, Loader)>>> data{'a': 42, 'b': [12.53, 123.64], 'c': [32, [1, 2, 3]]}

2. Using Symfony Parser: If you’re using Symfony’s version of YAML, you can do, like this:

imports:    - { resource: sub-directory/file.yml }    - { resource: sub-directory/another-file.yml }

3. Extends YAML to support file-based inheritance

But if you are using Ruby, there is a gem providing the functionality you are asking for by extending the ruby YAML library.

yaml_extend adds the method YAML#ext_load_file to YAML.

This method works like the original YAML#load_file, by extending it with file inheritance.


Basic Inheritance

Given the following both files are defined:

# start.ymlextends: 'super.yml'data:    name: 'Mr. Superman'    age: 134        favorites:        - 'Raspberrys'
# super.ymldata:    name: 'Unknown'    power: 2000    favorites:        - 'Bananas'        - 'Apples'

When you then call #ext_load_file

YAML.ext_load_file 'start.yml'

the returned YAML value results in

data:    name: 'Mr. Superman'    age: 134    power: 2000    favorites:        - 'Bananas'        - 'Apples'        - 'Raspberrys'


  1. https://stackoverflow.com/questions/528281/how-can-i-include-an-yaml-file-inside-another?rq=1
  2. https://github.com/yaml/pyyaml
  3. https://gist.github.com/joshbode/569627ced3076931b02f
  4. http://symfony.com/doc/current/components/yaml.html
  5. https://github.com/entwanderer/yaml_extend