Skip to content

Defined in header <fkYAML/node.hpp>

fkyaml::basic_node::serialize

static std::string serialize(const basic_node& node);

Serializes YAML node values recursively.
Currently, the serialization of mappings and sequences only supports block styles.
That means that, even if a deserialized source input contains container nodes written in flow styles, the serialization processes force them to be emitted in block styles.
Moreover, fkYAML unconditionally uses LFs as the line break format in serialization outputs and there is currently no way to change it to use CR+LFs.
This function serializes the given node parameter in the following format.

# A scalar
{[anchor] [tag] value | alias}

# A sequence key presented as an explicit key node.
? - <sequence value>
  - <another sequnce value>
: <scalar>

# A sequence value.
# Extra 2 spaces are inserted before the sequence indicators denoted as "- ".
# If an anchor and/or a tag are set to the sequence, they are put on the same line as the key.
<scalar>: [anchor] [tag]
  - <sequence scalar value>
  - [anchor] [tag] # A child sequence node.
    - <child sequence value>
  - [anchor] [tag] # A mapping node.
    <mapping>

# A mapping whose value is a scalar.
<scalar>: <scalar>

# A mapping key presented as an explicit key node.
? <mapping>
: <scalar>

# A mapping value whose value is a container node, either a mapping or a sequence.
# Extra 2 spaces are inserted before the value to indicate indentation.
# If an anchor and/or a tag are set to the mapping, they are put on the same line as the key.
<scalar>: [anchor] [tag]
  <mapping scalar key>: <mapping scalar value>
  <mapping scalar key>: [anchor] [tag] # A child mapping node.
    <child mapping scalar key>: <child mapping scalar value>

Parameters

node [in]
A basic_node object to be serialized.

Return Value

The resulting string object from the serialization of the node object.

Example
#include <iostream>
#include <fkYAML/node.hpp>

int main() {
    // create a basic_node object.
    fkyaml::node n = {
        {"foo", true},
        {"bar", {1, 2, 3}},
        {"baz", {{"qux", 3.14}, {"corge", nullptr}}},
        {{{true, 123}}, false},
        {{1.23, 4.56, 7.89}, 123456789}};
    // set tags to some nodes.
    n["foo"].add_tag_name("!!bool");
    n["bar"][1].add_tag_name("!<tag:yaml.org,2002:int>");
    // set an anchor name to a node.
    n["baz"].add_anchor_name("anchor");

    // serialize the basic_node object.
    std::cout << fkyaml::node::serialize(n) << std::endl;

    return 0;
}

output:

? - 1.23
  - 4.56
  - 7.89
: 123456789
? true: 123
: false
bar:
  - 1
  - !<tag:yaml.org,2002:int> 2
  - 3
baz: &anchor
  corge: null
  qux: 3.14
foo: !!bool true

See Also