Parsing yaml with yaml cpp

纵然是瞬间 提交于 2020-01-13 09:35:31

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/32492397/parsing-yaml-with-yaml-cpp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!