How do we get objects in boost property tree
-
25-06-2021 - |
Question
I need to understand and modify a sample code. I am stuck at some point and couldn't find any solution. Here is the code:
void foo(std::istream& input)
{
using boost::property_tree::ptree;
ptree pt;
boost::property_tree::read_json(input, pt);
BOOST_FOREACH(ptree::value_type &node, pt.get_child("some_nodes"))
{
std::string id;
unsigned int number1;
bool flag1;
bool flag2;
id = node.second.get<std::string>("id");
number1 = node.second.get<unsigned int>("number1");
flag1 = node.second.get<bool>("flag1");
flag2 = node.second.get<bool>("flag2");
}
}
Can somebody please tell me what does 'second' mean here ?
Here is the JSON example that the program reads:
{
"some_nodes" :
[
{
"id" : "vader",
"number1" : "1024",
"flag1" : "false",
"flag2" : "true",
},
{
"id" : "anakin",
"number1" : "4096",
"flag1" : "true",
"flag2" : "true",
}
]
}
One more question, I also get the following error when I try to compile the code. What does this mean, how can I solve it?
Invalid arguments '
Candidates are:
boost::foreach_detail_::foreach_reference<#0,#1>::type deref(const boost::foreach_detail_::auto_any_base &, boost::foreach_detail_::type2type<#0,#1> *)
'
Thanks a lot.
Solution
ptree::value_type is defined this way:
typedef std::pair< const Key, self_type > value_type;
so it's simply an std::pair. The root node of your JSON is the array "some_nodes". When you iterate your property tree you are iterating through all "some_nodes" children.
- first field is the key (implicit in this case since you are iterating all the root child nodes). I suppose in your case node.first is always "some_nodes".
- second is the value (a child node of the key: another ptree). In this case at each iteration second is the i-th unnamed object of your array.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow