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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With