Search code examples
c++parsingdictionaryyamlyaml-cpp

How to parse a file with yaml-cpp


I have a yaml file that looks like this:

construction_cone_1:
  model: construction_cone
  model_type: sdf
  position: [ 1.2, 3.4, 0.0 ]
  orientation: [ 0.0, 0.0, 0 ]
  
construction_cone_2:
  model: construction_cone
  model_type: sdf
  position: [ 3.0, 7.0, 0.0 ]
  orientation: [ 0.0, 0.0, 0 ]
 
...

I'm following this tutorial to parse it in my c++ application.

What I understood so far is that, as it is structured, the file is loaded as a map into a YAML::Node. So, I guess, a good way to read it is:

YAML::Node map = YAML::LoadFile(file_path);
  for(YAML::const_iterator it=map.begin(); it!=map.end(); ++it){
    const std::string &key=it->first.as<std::string>();

This gives me "construction_cone_1" for the first entry and so on. By following this logic I'm not able to figure out how to read the remainder. In particular, for each entry of the map, I'm interested in reading the object position.


Solution

  • I guess I underestimated the power of the library. It turns out that doing so solves the problem:

      YAML::Node map = YAML::LoadFile(filename);
      for(YAML::const_iterator it=map.begin(); it!=map.end(); ++it){
        const std::string &key=it->first.as<std::string>();
    
        Eigen::Vector2f pos;
        YAML::Node attributes = it->second;
        YAML::Node position = attributes["position"];
        for(int i=0; i<2; ++i){
          pos(i) = position[i].as<float>();
        }
    
        ...
      }