YAML is a human-readable data serialization language. With it, you can create easily readable documents that can be consumed by a variety of programming languages.
For example, here’s a map of baseball teams per league:
american:
- Boston Red Sox
- Detroit Tigers
- New York Yankees
national:
- New York Mets
- Chicago Cubs
- Atlanta BravesAnd a data dictionary specification:
yaml.load() parses a YAML document from a string:
yaml.load_file() and read_yaml() read YAML
from a file or connection.
A YAML scalar is the basic building block of YAML documents. The parser automatically determines the type:
A YAML sequence is a list of elements. If all elements are uniform,
yaml.load() returns a vector of that type. Otherwise, it
returns a list:
A YAML map is a list of paired keys and values. By default,
yaml.load() returns a named list:
Since YAML map keys can be almost anything (not just strings), you
can preserve the data type of keys with
as.named.list = FALSE. This creates a keys
attribute instead of coercing keys to strings:
You can customize parsing with handler functions. Handlers are passed
to yaml.load() as a named list, where each name is the YAML
type to handle:
# Add 100 to all integers
yaml.load("123", handlers = list(int = function(x) as.integer(x) + 100))
#> [1] 223Sequence handlers receive a list and can transform it:
as.yaml() converts R objects to YAML strings:
write_yaml() writes the result directly to a file or
connection.
Control indentation depth (default is 2):
By default, sequences within a mapping are not indented:
Set indent.mapping.sequence = TRUE to indent them:
Specify custom handler functions for R object classes:
For YAML 1.2-like logical output, use
verbatim_logical:
Character vectors with class "verbatim" are not quoted
except when required by the YAML specification: