Skip to content

Instantly share code, notes, and snippets.

@lsloan
Last active September 2, 2022 12:43
Show Gist options
  • Save lsloan/dedd22cb319594f232155c37e280ebd7 to your computer and use it in GitHub Desktop.
Save lsloan/dedd22cb319594f232155c37e280ebd7 to your computer and use it in GitHub Desktop.
YAML Path (`yamlpath` on PyPI) examples
# Expanding on YAML Path basic Python library example from
# https://github.com/wwkimball/yamlpath/blob/master/README.md#searching-for-yaml-nodes
from types import SimpleNamespace
from yamlpath import Processor
from yamlpath import YAMLPath
from yamlpath.common import Parsers
from yamlpath.exceptions import YAMLPathException
from yamlpath.wrappers import ConsolePrinter
from yamlpath.wrappers import NodeCoords
loggingArgs = SimpleNamespace(quiet=True, verbose=False, debug=False)
logger = ConsolePrinter(loggingArgs)
yamlParser = Parsers.get_yaml_editor()
yamlFilename = 'your-file.yaml'
(yamlData, documentLoaded) = Parsers.get_yaml_data(yamlParser, logger,
yamlFilename)
if not documentLoaded:
# an error message has already been printed via ConsolePrinter
exit(1)
processor = Processor(logger, yamlData)
dataYamlPath = YAMLPath('see.documentation.for.example')
try:
for nodeCoordinate in processor.get_nodes(dataYamlPath, mustexist=True):
print(f'Got {repr(nodeCoordinate)} from {repr(dataYamlPath)}.')
# Unwrapping is the undocumented step needed to access node data
nodeData = NodeCoords.unwrap_node_coords(nodeCoordinate)
propertyName = 'fubar'
propertyValue = nodeData.get(propertyName)
print(f'"{propertyName}": {repr(propertyValue)}')
# Do something with each node_coordinate.node (the actual data)
except YAMLPathException as ex:
logger.error(ex)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment