parsing the YAML file
Hello All,
I'm new to ROS and C++.
here's the question:
so, my yaml
file looks like this:
parameters:
status:
stage1:
distance: 4000
color1:
r: 0
g: 255
b: 0
color2:
r: 0
g: 0
b: 0
stage2:
distance: 8000
color1:
r: 0
g: 0
b: 255
color2:
r: 0
g: 0
b: 0
i want to read the struct stage1 and stage2 and their members( first status and then its member(children) like distance, color1 and color2 ) in my main.cpp
.
i have configured it in XmlRpc::XmlRpcValue
way to read the value.
at the moment i can just read parameters and its member, like:
parameters:
distance: 4000
color1:
r: 0
g: 12
b: 0
color2:
r: 255
g: 0
b: 0
but i'm unable to read its member's member.
is it possible to read first stages
and then its members(Children) like distance
, color1
and color2
? if not possible, i can maybe remove status
and have just the stages
.
or is there any other way to read the file where distance
, color1
and color2
can be read based on their parent(like stage1
and stage2
)?
Thankyou so much in Advance!!
Asked by specie on 2022-12-20 12:05:30 UTC
Answers
Based on this StackOverflow Q&A, you can use this piece of code:
YAML::Node root = /* ... */;
YAML::Node node = root["Node"];
// We now have a map node, so let's iterate through:
for (auto it = node.begin(); it != node.end(); ++it) {
YAML::Node key = it->first;
YAML::Node value = it->second;
if (key.Type() == YAML::NodeType::Scalar) {
// This should be true; do something here with the scalar key.
}
if (value.Type() == YAML::NodeType::Map) {
// This should be true; do something here with the map.
}
}
to parse nested YAML like this one below
Node:
Foo:
f1 : one
f2 : two
Bar:
b1 : one
b2 : two
Other nice SO answer is here - code snippet below.
This loop:
for (YAML::const_iterator ti = attributes.begin(); ti !=
attributes.end(); ++ti)
is iterating over a map node. Therefore, the iterator points to a key/value pair. Your next line:
const YAML::Node& frame = *ti;
dereferences it as a node. Instead, you need to look at its key/value nodes:
const YAML::Node& key = ti->first; const YAML::Node& value = ti->second;
yaml-cpp
allows iterators to both point to nodes and key/value pairs because it can be a map or a sequence (or a scalar), and it's implemented as a single C++ type.
Asked by ljaniec on 2022-12-21 06:00:01 UTC
Comments