Access YAML Values from Frontmatter Using Python
Python
Access nested (or not) YAML values using Python. Used within a Makefile to set variables from either Markdown frontmatter or YAML config files.
Uses the Python 3 yaml
module’s load_all
method - this is necessary if accessing YAML within a frontmatter block (e.g. at the start of a markdown file), since the normal frontmatter delimiters cause the Python module to treat the YAML block as the first in a series of YAML documents.
The function receives a list of YAML keys key_list
ordered from highest to lowest level, allowing access to nested elements.
For example:
---
name: Rocky
address:
line 1: 22 Acacia Ave
line 2: London
---
To access the value “London”, run ./yaml_access.py file.md address "line 2"
.
To access the value “Rocky”, run ./yaml_access.py file.md name
.
#!/usr/bin/env python3
# yaml_access.py
import sys, os, yaml
def main(filename, key_list):
project_dir = os.path.realpath('.')
filepath = os.path.join(project_dir, filename)
with open(filepath, "r") as f:
# Make a dict from the first YAML block
data = next(yaml.load_all(f, Loader=yaml.FullLoader))
# If there are multiple keys, we need to step down a hierarchy of keys
# to reach the correct value. At each iteration, set data to be a new
# simpler dict (or the final value if we're at the last key) by accessing
# the value by it's key.
for key in key_list: data = data[key]
print(data)
if __name__ == '__main__':
main(sys.argv[1], sys.argv[2:])
comments powered by Disqus