Search code examples
c++yamlyaml-cpp

How to create the top object with yaml-cpp?


I am trying to create a config file for my application using yaml-cpp, I am able to create map by

    YAML::Emitter emitter;
    emitter << YAML::BeginMap;
    emitter << YAML::Key << "Autoplay" << YAML::Value << "false";
    emitter << YAML::EndMap;

    std::ofstream ofout(file);
    ofout << emitter.c_str();

which outputs something like,

var1: value1
var2: value2

But how would I make the top object like,

Foo:
  var1: value1
  var2: value2

Bar:
  var3: value3
  var4: value4

and so on.. How do I get the Foo and the Bar like in the above code.


Solution

  • What you want to achieve is a map containing two keys Foo and Bar. Each of these containing a map as a value. The code below show you how you can achieve that:

    // gcc -o example example.cpp -lyaml-cpp
    #include <yaml-cpp/yaml.h>
    #include <fstream>
    
    int main() {
      std::string file{"example.yaml"};
    
      YAML::Emitter emitter;
      emitter << YAML::BeginMap;
    
      emitter << YAML::Key << "Foo" << YAML::Value;
      emitter << YAML::BeginMap; // this map is the value associated with the key "Foo"
      emitter << YAML::Key << "var1" << YAML::Value << "value1";
      emitter << YAML::Key << "var2" << YAML::Value << "value2";
      emitter << YAML::EndMap;
    
      emitter << YAML::Key << "Bar" << YAML::Value;
      emitter << YAML::BeginMap; // This map is the value associated with the key "Bar"
      emitter << YAML::Key << "var3" << YAML::Value << "value3";
      emitter << YAML::Key << "var4" << YAML::Value << "value4";
      emitter << YAML::EndMap;
    
      emitter << YAML::EndMap; // This ends the map containing the keys "Foo" and "Bar"
    
      std::ofstream ofout(file);
      ofout << emitter.c_str();
      return 0;
    }
    

    You have to see these sorts of structures with a recursive mindset. This code will create the example you gave.