WyllianNeo
WyllianNeo

Reputation: 363

How can I include a specific data from YAML file inside another?

I have a very similar structure and scenario to this question and it help me a lot, but I'm looking for a more specific situation, I wanna include to my yaml file just a data from another yaml file, not the complete file. Something like:

UPDATED: I correct the structure of files below to describe properly my scenario, sorry.

foo.yaml

a: 1
b:
    - 1.43
    - 543.55
    - item : !include {I wanna just the [1, 2, 3] from} bar.yaml

bar.yaml

- 3.6
- [1, 2, 3]

Right now, I'm importing all the second file, but I don't need all and don't figure it out the proper solution since yesterday. Below is my actual structure:

foo.yaml

variables: !include bar.yaml #I'm importing the entire file for now and have to navegate in that to get what I need.
a: 1
b:
    - 1.43
    - 543.55

Upvotes: 0

Views: 5413

Answers (1)

flyx
flyx

Reputation: 39758

You can write your own custom include constructor:


bar_yaml = """
- 3.6
- [1, 2, 3]
"""

foo_yaml = """
variables: !include [bar.yaml, 1]
a: 1
b:
    - 1.43
    - 543.55
"""

def include_constructor(loader, node):
  selector = loader.construct_sequence(node)
  name = selector.pop(0)
  # in actual code, load the file named by name.
  # for this example, we'll ignore the name and load the predefined string
  content = yaml.safe_load(bar_yaml)
  # walk over the selector items and descend into the loaded structure each time.
  for item in selector:
    content = content[item]
  return content

yaml.add_constructor('!include', include_constructor, Loader=yaml.SafeLoader)

print(yaml.safe_load(foo_yaml))

This !include will treat the first item in the given sequence as file name and the following items as sequence indexes (or dictionary keys). E.g. you can do !include [bar.yaml, 1, 2] to only load the 3.

Upvotes: 2

Related Questions