Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing yaml with yaml cpp

Tags:

c++

yaml-cpp

I am trying to parse a yaml usign yaml-cpp. This is my yaml:

--- 
configuration: 
  - height: 600
  - widht:  800
  - velocity: 1
  - scroll: 30
types: 
  - image: resources/images/grass.png
    name: grass
  - image: resources/images/water.png
    name: water
 version: 1.0

When I do

YAML::Node basenode = YAML::LoadFile("./path/to/file.yaml");
int height;
if(basenode["configuration"])
    if(basenode["configuration"]["height"]
       height = basenode["configuration"]["height"].as<int>();
    else
       cout << "The node height doesn't exist" << endl;
else
    cout << "The node configuration doesn't exist" <<  endl;

I am getting the message: "The node height doesn't exist". How can I access to that field (and the others?)

Thanks a lot!

like image 985
jmoren Avatar asked Sep 10 '15 03:09

jmoren


1 Answers

The syntax you've used with the - creates array elements. This means that you're creating (in JSON notation):

{configuration: [{height: 600}, {width: 800}, {velocity: 1}, {scroll: 30}]}

But what you want is:

{configuration: {height: 600, width: 800, velocity: 1, scroll: 30}}

Luckily the solution is easy. Just remove the erroneous - characters:

---
configuration: 
  height: 600
  width:  800
  velocity: 1
  scroll: 30
types: 
  - image: resources/images/grass.png
    name: grass
  - image: resources/images/water.png
    name: water
version: 1.0

Note that I've also fixed a typo of widht to width and removed an extraneous space before version: 1.0

If you're wondering how you would actually access your configuration as it is now, you'd have to do an array access:

int height = basenode["configuration"][0]["height"].as<int>();
int height = basenode["configuration"][1]["width"].as<int>();

Obviously this would be rather nasty if you actually wanted it like this since it means that you no longer get to use keys but would have to either have order matter or reprocess the config to get rid of the array level.

like image 107
Corbin Avatar answered Nov 17 '22 17:11

Corbin