Reputation: 201
--- #File A
- Lunch: &01
- Chicken
- Rice
- Sallad
...
--- #File B
- Monday: *01
- Tuesday: *01
...
For example File A is in C:drive in my PC and File B is in D:drive.
How can I export the anchors Using YAML?
Upvotes: 20
Views: 12815
Reputation: 1373
I used a workaround by creating a suitable constructor to import values from other YAML files:
# defaults.yaml
values:
a: 5
# config.yaml
test1:
- !r defaults.yaml#values.a
test2: !r defaults.yaml#values.a
test3: !r defaults.yaml#values
Parsing using pyyaml
:
import yaml
def get_nested_value(data, path):
keys = path.split(".")
current_value = data
for key in keys:
current_value = current_value.get(key)
if current_value is None:
return None
return current_value
def read_constructor(loader, node):
fn, path = node.value.split("#")
with open(fn, "r") as f:
data = yaml.load(f, Loader=yaml.SafeLoader)
return get_nested_value(data, path)
Loader = yaml.SafeLoader
Loader.add_constructor("!r", read_constructor)
if __name__ == "__main__":
fn = "config.yaml"
with open(fn, "r") as f:
config = yaml.load(f, Loader=Loader)
print(config)
Output:
{'test1': [5], 'test2': 5, 'test3': {'a': 5}}
This is not 100% related to your questions, but it is an easy way to import values from files (path are defined relative to your target YAML file).
Upvotes: 1
Reputation: 667
You can't share anchors/aliases between documents; Chapter 9.1 of the YAML 1.2 spec explicitly states that each document is completely independent.
Upvotes: 22