Search code examples
yamlyaml-cpp

yaml-cpp create a new empty map?


How can I create a new YAML parameter that is an empty map (the use-case is to populate it in some later part of the code)? Minimal working example:

YAML::Node node  = YAML::LoadFile("config.yaml");
node["new_map"] = "{}"; // this creates a string, but I want a map
std::ofstream fout("config.yaml");
fout << node;

Solution

  • You can use the YAML::Node constructor that takes a NodeType as an argument to force it to be a Map:

    #include <yaml-cpp/yaml.h>
    
    #include <iostream>
    
    int main() {
        YAML::Node node;
        node["new_map"] = YAML::Node(YAML::NodeType::Map);
        std::cout << node;
    }
    

    Output:

    new_map:
      {}