CompSciGuy139 CompSciGuy139 - 3 months ago 18
YAML Question

confused by YAML::NodeType::Undefined with yaml-cpp

I have a test yaml file that I am trying to parse using yaml-cpp.

test.yaml

testConfig:
# this points to additional config files to be parsed
includes:
required: "thing1.yaml"
optional: "thing2.yaml"
#some extraneous config information
foo: 42
bar: 394
baz: 8675309


I parse it I get
testConfig.Type()
returns
YAML::NodeType::Map
. And this is expected behavior.

Then, I try to parse the includes to get the required or optional values I can't iterate because
includes.Type()
returns
YAML::NodeType::Undefined
. I'm really new to yaml and to yaml-cpp so any help showing me where I am going wrong would be appreciated.

parsing code:

{includes and other such nonsense}
.
.
.
YAML::Node configRoot = YAML::LoadFile(path.c_str() );
if( configRoot.IsNull() )
{
SYSTEM_LOG_ERROR("Failed to load the config file: %s.",
path.c_str());
return false;
}

YAML::Node includes = configRoot["includes"];
/* ^^^^^^^^^^^^^^^
* I believe that here lies the issue as includes is undefined and
* therefore I cannot iterate over it.
*/
for( auto it = include.begin(); it != include.end(); ++it )
{
// do some fantastically brilliant CS voodoo!
}
.
.
.
{ more C++ craziness to follow }

Answer

Well, your top-level YAML document does indeed not include a key named includes. It only contains a key named testConfig. You should access that first:

// ...
YAML::Node configRoot = YAML::LoadFile(path.c_str())["testConfig"];
// ...

Or, if you want to explicitly check if testConfig exists:

// ...
YAML::Node configRoot = YAML::LoadFile(path.c_str());
// do check her as in your code
YAML:Node testConfig = configRoot["testConfig"];
// check if testConfig is a mapping here
YAML::Node includes = testConfig["includes"];
// ...