yq: Command-line YAML/XML/TOML Processor

3.4.3 · active · verified Thu Apr 09

yq is a Python-based command-line processor for YAML, XML, and TOML documents, acting as a lightweight wrapper that transparently converts these formats to JSON and pipes them to the `jq` command-line tool for querying and manipulation. It's currently at version 3.4.3 and maintains an active release cadence with regular updates and fixes.

Warnings

Install

Quickstart

The `yq` library primarily provides command-line utilities (`yq`, `xq`, `tomlq`). To use it programmatically in Python, you typically invoke these commands via `subprocess`. This example demonstrates how to create a YAML file, extract a value, and perform a transformation using `yq`.

import subprocess
import os

# Create a sample YAML file
yaml_content = """
name: Jane Doe
age: 28
city: San Francisco
details:
  occupation: Developer
  hobbies: [coding, gaming]
"""
with open("sample.yaml", "w") as f:
    f.write(yaml_content)

print("--- Original YAML ---")
print(yaml_content)

# Process the YAML file using yq to extract the name
try:
    # Example 1: Get the name
    result_name = subprocess.run(
        ["yq", ".name", "sample.yaml"],
        capture_output=True, text=True, check=True
    )
    print(f"\n--- Extracted Name ---
{result_name.stdout.strip()}")

    # Example 2: Update the age and city using a jq-like expression
    result_updated = subprocess.run(
        ["yq", '.age = 29 | .city = "Seattle"', "sample.yaml"],
        capture_output=True, text=True, check=True
    )
    print("\n--- Updated YAML (age 29, city Seattle) ---")
    print(result_updated.stdout.strip())

except FileNotFoundError:
    print("\nError: 'yq' command not found. Please ensure yq (this Python package and the external 'jq' binary) is installed and in your system PATH.")
except subprocess.CalledProcessError as e:
    print(f"\nError processing YAML with yq: {e}")
    print(f"Stderr: {e.stderr.strip()}")
finally:
    # Clean up the sample file
    if os.path.exists("sample.yaml"):
        os.remove("sample.yaml")

view raw JSON →