| Did you know ... | Search Documentation: |
| Pack logtalk -- logtalk-3.98.0/docs/handbook/_sources/libraries/yaml.rst.txt |
.. _library_yaml:
yaml
The yaml library provides predicates for parsing and generating data
in the YAML format:
It includes parsing and generation of simple scalar values, lists, mappings, and nested structures.
Open the `../../apis/library_index.html#yaml <../../apis/library_index.html#yaml>`__ link in a web browser.
To load all entities in this library, load the loader.lgt file:
::
| ?- logtalk_load(yaml(loader)).
To test this library predicates, load the tester.lgt file:
::
| ?- logtalk_load(yaml(tester)).
Parsing ~~~~~~~
The parse/2 predicate parses YAML content from various sources into a structured Logtalk term representation.
.. code:: logtalk
parse(+Source, -YAML)
Sources can be:
file(Path) - parse YAML from a filestream(Stream) - parse YAML from an open streamcodes(Codes) - parse YAML from a list of character codeschars(Chars) - parse YAML from a list of charactersatom(Atom) - parse YAML from an atom
The parsed YAML is returned as a compound term with the functor
yaml/1.
Generating ~~~~~~~~~~
The generate/2 predicate generates YAML output from a structured term.
.. code:: logtalk
generate(+Sink, +YAML)
Sinks can be:
file(Path) - write YAML to a filestream(Stream) - write YAML to an open streamcodes(Codes) - get YAML as a list of character codeschars(Chars) - get YAML as a list of charactersatom(Atom) - get YAML as an atom
The input must be a compound term representing YAML data (e.g.,
yaml([...]) for mappings, [...] for sequences).
Multi-Document Parsing ~~~~~~~~~~~~~~~~~~~~~~
The parse_all/2 predicate parses all YAML documents from a source into a list.
.. code:: logtalk
parse_all(+Source, -YAMLs)
Documents are separated by --- markers and optionally terminated by
... markers. Returns a list of YAML terms, even for single-document
sources.
Multi-Document Generation
The ``generate_all/2`` predicate generates YAML output with multiple
documents.
.. code:: logtalk
generate_all(+Sink, +YAMLs)
Takes a list of YAML terms and generates output with ``---`` separators
between documents. For a single document, no separator is added.
Data Representation
-------------------
YAML data is represented using the following mappings:
=============== ==========================
YAML Value Logtalk Representation
=============== ==========================
``null`` ``'@'(null)``
``true`` ``'@'(true)``
``false`` ``'@'(false)``
Number (42) ``42``
String ("text") ``text`` (as atom)
Array/List ``[item1, item2, ...]``
Mapping/Object ``yaml([key1-val1, ...])``
=============== ==========================
Examples
--------
Parsing a Simple YAML String
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: logtalk
?- parse(atom('name: John\nage: 30'), YAML).
YAML = yaml([name-'John', age-30]).
Parsing a YAML List
~~~~~~~~~~~~~~~~~~~
.. code:: logtalk
?- parse(codes([0'-, 0' , 0'a, ...]), YAML).
YAML = yaml([apple, banana, orange]).
Parsing a YAML File
~~~~~~~~~~~~~~~~~~~
.. code:: logtalk
?- parse(file('config.yaml'), YAML).
% Reads and parses config.yaml
Generating YAML from a Term
~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: logtalk
?- generate(atom(Result), yaml([title-'Project', version-1])).
Result = '{title:Project,version:1}'.
Generating YAML to a File
.. code:: logtalk
?- Data = yaml([name-'Alice', score-95]),
generate(file('output.yaml'), Data).
% Writes YAML data to output.yaml
Working with Nested Structures ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. code:: logtalk
?- YAML = yaml([
person-yaml([
name-'Bob',
age-25,
skills-[logtalk, prolog, python]
])
]),
generate(atom(Result), YAML).
% Generates YAML representation of nested structure
The library currently supports a subset of YAML 1.2 features suitable for common configuration and data serialization tasks:
Scalars
'...'), and double-quoted
("...")Mark McGwire: 65)42), signed positive (+12345), octal
(0o14), hexadecimal (0xC)3.14), scientific notation (1.23e+3).inf, -.inf, .nan (represented as
'@'(inf), '@'(-inf), '@'(nan))true and falsenull or empty values- indicator with proper indentation[ ] syntax with comma separationkey: value syntax with proper indentation{ key: value } syntax| style preserves newlines exactly> style folds newlines into spaces- (strip), + (keep), default (clip) for
trailing newlines&name to define a reusable node*name to reference a previously defined anchor<< to merge mappings from aliases--- is recognized and skipped... is recognized and handled--- or ... separated
documents (via parse_all/2)# and inline comments after values!tag, !!type, and !<uri> tags are recognized and
skipped
Escape Sequences (in double-quoted strings)
\\ - backslash\" - double quote\/ - forward slash\n - newline\t - tab\r - carriage return\b - backspace\f - form feed\0 - null character\xXX - hex escape (2 hex digits)\uXXXX - Unicode escape (4 hex digits)The following YAML features are not currently supported:
? indicator for multi-line or complex keys[*alias1, *alias2] (aliases work in
block context)<<: [*a, *b] (single alias merge
works)%YAML and %TAG directivesThe library raises the following errors:
instantiation_error - when a required argument is a variabledomain_error(yaml_source, Source) - when an invalid source is
provideddomain_error(yaml_sink, Sink) - when an invalid sink is provideddomain_error(yaml_term, Term) - when an invalid YAML term is
providedyaml_protocol.lgt - Defines the protocol for YAML parser/generatoryaml.lgt - Main implementation objectloader.lgt - Library loadertester.lgt - Test runnertest_files/ - Directory containing test files and sample YAML
files for testingThe library includes several sample YAML files for testing:
simple.yaml - Simple key-value pairslist.yaml - A YAML listnested.yaml - Nested structurescomplex.yaml - Lists of mappingsconfig.yaml - Configuration file examplemetadata.yaml - Metadata example with quoted stringsThe YAML library can be integrated with other Logtalk libraries:
os library for file path handlingreader library for stream managementterm_io library for term serializationPotential future enhancements may include:
!!binary for base64
decoding)? indicatorjson_lines library for JSON Lines format parsing and generation