YAML
YAML 1.2 is read and written by the
yaml package, which has
the same shape as the json and toml modules: a
YamlValue to look values up in and change, clang-style errors at the
line and column, documents that keep their comments when edited, and
struct conversion with the serialize
attributes. It is a package rather than part of the runtime because few
programs need YAML; add it with
pepper package add justinboswell/pepper-yaml --name yaml.
import yaml;
main(): int {
var parsed = yaml.parse("server:\n port: 8080\n debug: no\n", path = "config.yaml");
if (parsed.is_err()) {
print(parsed.error().to_string());
return 1;
}
var root = parsed.value();
print(root["server"]["port"].as_int().value()); # 8080
print(root["server"]["debug"].as_string().value()); # no
root["server"]["port"] = yaml.YamlValue.Integer(9090);
print(root.to_string());
return 0;
}
- The core schema:
yes,no,onandoffare strings, not booleans, soNO(Norway) staysNO. - Safe for untrusted text: only the core schema’s tags (
!!str,!!int, …) are read, and any other tag is an error; aliases may not stand for more thanmax_alias_nodesnodes, which stops the “billion laughs” attack. - Merge keys:
yaml.parse(text, merge_keys = true)applies YAML 1.1’s<<(<<: *defaults), which CI and compose files use to reuse a mapping; the mapping’s own keys win, and merged nodes count towardmax_alias_nodes. By default<<is an ordinary key, as YAML 1.2 says. - Several documents in one stream (
---) are read byyaml.parse_alland written byyaml.write_all. yaml.parse_documentkeeps comments, key order, flow or block style and scalar styles through edits, asjson.parse_documentkeeps a JSONC file’s comments.yaml.encodeandyaml.decode<T>convert structs exactly asjson.encodeandjson.decodedo.
The package’s README lists what it reads and its limits: a mapping’s keys are strings, and there is no streaming reader yet.