Noel Bahdy
Noel Bahdy

Reputation: 29

How to get specific category names from yaml file?

I am using c++ and have a yaml file that looks like this:

Food:
  Apple:
    - Type: grannysmith
  BellPepper:
    - Type: Red
    - Type: Green
  Sandwich:
    - Type: Ham

I need to parse it so that I get a string vector listing only the food names:
output: "Apple", "BellPepper","Sandwich"

My code looks like this so far:

YAML::Node node = YAML::LoadFile(configYamlPath)["Food"];    
std::vector<std::string> items;    
for (YAML::Node n : node){    
    items.push_back(n.as<std::string>());    
}    

How would I go about getting those specific keys?

Upvotes: 0

Views: 287

Answers (1)

md5i
md5i

Reputation: 3083

Here, node is a YAML map. When you iterate over a YAML map, you get back std::pair<YAML::Node, YAML::Node>, which are key, value pairs. So, you want:

for (auto n : node) {
    YAML::Node &key = p.first;
    // Do something with the key here
}

(In actuality, the value returned by dereferencing the iterators is a type that inherits both from YAML::Node and std::pair<YAML::Node, YAML::Node>, which is why your current code doesn't fail to compile. But that is an implementation detail.)

Upvotes: 2

Related Questions