YAMLPath

3.9.0 · active · verified Fri Apr 17

YAMLPath is a Python library and collection of command-line tools for powerful, intuitive manipulation of YAML, JSON, and compatible data. It provides get, set, merge, validate, scan, convert, and diff processors using a command-line friendly path syntax. The library is actively maintained with frequent releases, currently at version 3.9.0, supporting modern Python versions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load YAML data using `ruamel.yaml`, create `YAMLPath` objects for specific nodes, and then use `Processor` to get, set, and append values within the data structure. A logger is required for `Processor`.

import io
from ruamel.yaml import YAML
from yamlpath import YAMLPath
from yamlpath.processor import Processor
import logging

# Configure a basic logger (required by Processor)
logger = logging.getLogger()
logger.setLevel(logging.INFO)

yaml_data = """
config:
  name: My App
  version: 1.0.0
  features:
    - auth
    - logging
  settings:
    debug: false
"""

# Load YAML data
yaml = YAML()
data = yaml.load(io.StringIO(yaml_data))

# Initialize Processor with the data and logger
processor = Processor(logger, data)

# Example 1: Get a value
path_to_name = YAMLPath("$.config.name")
for value, parent, key in processor.get_nodes(path_to_name):
    print(f"Current config name: {value}")

# Example 2: Set a value
path_to_version = YAMLPath("$.config.version")
processor.set_value(path_to_version, "1.1.0")
print(f"Set config version to 1.1.0")

# Example 3: Add an item to a list
path_to_features = YAMLPath("$.config.features")
processor.append_value(path_to_features, "analytics")
print(f"Added 'analytics' to features")

# Output the modified YAML
output_stream = io.StringIO()
yaml.dump(data, output_stream)
print("\nModified YAML:\n" + output_stream.getvalue())

view raw JSON →