Parsing YAML
Parsing YAML¶
This guide covers all ways to parse YAML with pyrs-yaml.
Basic Parsing¶
Parse a YAML String¶
import pyrs_yaml
doc = pyrs_yaml.parse("key: value") # (1)!
print(doc.get("key")) # value
parse()returns aYamlDocumentthat preserves comments, anchors, and formatting.
Parse with Options¶
# Disable merge key resolution (keep <<: *alias as-is)
doc = pyrs_yaml.parse(yaml_text, resolve_merges=False)
Parse a YAML File¶
doc = pyrs_yaml.parse_file("config.yaml")
print(doc.get("name"))
Parse Multiple Documents¶
# YAML with --- separators
yaml_text = """
---
name: first
---
name: second
"""
docs = pyrs_yaml.parse_all_docs(yaml_text)
print(len(docs)) # 2
print(docs[0].get("name")) # first
print(docs[1].get("name")) # second
One document per call
parse, parse_file and safe_load read one document. An input carrying a second is
refused with a YamlParseError whose message starts multi-document-input: and names where
that document begins. The alternative was answering with one document of the stream and
discarding the rest: a: 1\n---\nb: 2 answered b: 2, and a: 1\n--- answered null.
parse_all_docs and safe_loads above are the routes that read a stream, and parse_stream
the one that reads its events; PyYAML and ruamel.yaml refuse the same inputs on their
single-document calls. A leading ---, a trailing ... and a %YAML directive each still
read as one document.
PyYAML-Compatible Parsing¶
PyYAML-compatible parsing
Use safe_load to get native Python types (dict, list, str, int,
etc.) instead of a YamlDocument. For multiple documents, safe_loads
returns a list of parsed objects.
# Returns native Python types (dict, list, str, int, etc.)
data = pyrs_yaml.safe_load("key: value")
print(data) # {'key': 'value'}
# Multiple documents
docs = pyrs_yaml.safe_loads("a: 1\n---\nb: 2")
print(len(docs)) # 2
Acceptable Input Types¶
pyrs-yaml accepts three input forms:
-
str— standard YAML string - :material-binary:
bytes— valid UTF-8 encoded bytes -
strwith BOM — handled correctly
doc = pyrs_yaml.parse("key: value")
doc = pyrs_yaml.parse(b"key: value")
Error Handling¶
try:
doc = pyrs_yaml.parse("invalid: yaml: [")
except pyrs_yaml.YamlParseError as e:
print(f"Parse error: {e}")
Supported Data Types¶
pyrs-yaml correctly parses all YAML 1.2 scalar types:
| Type | Example | Python Type |
|---|---|---|
| String | hello |
str |
| Integer | 42, 0x1A, 0o77 |
int |
| Float | 3.14, 1.23e-4 |
float |
| Boolean | true, false |
bool |
| Null | null, ~ |
None |
| Infinity | .inf, -.inf |
float |
| NaN | .nan |
float |
See Also¶
- Serialization — Convert documents back to YAML strings
- In-Place Editing — Modify parsed documents without losing formatting
- Custom Schemas — Define custom type resolution rules