ruamel.yaml.string

0.1.1 · active · verified Thu Apr 16

ruamel.yaml.string is a plugin for the `ruamel.yaml` YAML parser/emitter library. It extends the `ruamel.yaml.YAML` instance by adding `dump_to_string` (and its alias `dumps`) methods, allowing users to serialize YAML documents directly into a Python string instead of writing to a file-like object. The current version is 0.1.1, last updated in May 2023, and its release cadence is tied to `ruamel.yaml` and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `ruamel.yaml.YAML` with `typ=['rt', 'string']` to enable the `dump_to_string` and `dumps` methods, which return the YAML document as a Python string. It also shows the `add_final_eol` parameter for controlling the trailing newline behavior.

from ruamel.yaml import YAML
import sys

# Instantiate YAML with the 'string' type to enable dump_to_string/dumps
yaml = YAML(typ=['rt', 'string'])

data = {
    'name': 'John Doe',
    'age': 30,
    'hobbies': ['reading', 'hiking', 'coding'],
    'address': {
        'street': '123 Main St',
        'city': 'Anytown'
    }
}

# Dump to string using dump_to_string
yaml_string = yaml.dump_to_string(data)
print('YAML as string (dump_to_string):')
print(yaml_string)

# Dump to string using dumps (alias for dump_to_string)
yaml_string_alias = yaml.dumps(data, add_final_eol=True)
print('\nYAML as string (dumps with final EOL):')
print(yaml_string_alias)

view raw JSON →