Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost : Just iterate over elements of a ptree

This should be simple (I'm just learning boost so I'm missing something)

I have read in some simple JSON using json_read and now have a ptree. All the examples on the web show using ptree.get("entry_name") to obtain an entry. All I want to do is something like:

 ptree pt;
 read_json(ss,pt);

 BOOST_FOREACH(ptree::value_type &v, pt)
 {
   std::cout << v.{entry_name} << v.{value}
 }

i.e. loop through the ptree and write out each name (i.e. what you put into pt.get()) and it's corresponding value.

Sorry if this is simple

Ross

like image 335
Ross W Avatar asked Apr 14 '11 14:04

Ross W


4 Answers

I was searching the same thing, and couldn't find the answer anywhere. It turned out to be pretty simple indeed:

ptree pt;
/* load/fill pt */
for(iterator iter = pt.begin(); iter != pt.end(); iter++)
{
  std::cout << iter->first << "," << iter->second.data() << std::endl;
}

iter->first is the entry name, and iter->second.data() is the entry value of the first level. (You can then re-iterate with iter->second.begin()/end() for deeper levels.)

Further, if one such node in this iteration is not a terminal node and is itself a ptree, you can get that as ptree from this iterator itself : ptree subPt = iter->second.get_child("nodeName");

like image 102
mr_georg Avatar answered Oct 24 '22 10:10

mr_georg


I'm having troubles with ptree as well, but perhaps this can help: Check out boost's ptree quick tutorial

v.{entry_name}
would be
v.first

and

v.{value}
v.second.data()

Would that work?

like image 42
Sam Avatar answered Oct 24 '22 08:10

Sam


Here's a great example of how to iterate a ptree using BOOST_FOREACH http://akrzemi1.wordpress.com/2011/07/13/parsing-xml-with-boost/

for direct access using the normal "get" functions look at the example from boost: http://www.boost.org/doc/libs/1_51_0/doc/html/boost_propertytree/tutorial.html

the documentation page is located here: http://www.boost.org/doc/libs/1_51_0/doc/html/boost/property_tree/basic_ptree.html I know its not very well documented but it is helpful.

like image 20
Alex Avatar answered Oct 24 '22 09:10

Alex


Old thread, but here's a C++11 version of mr_georg's answer with range-based for loops:

ptree pt;
/* load/fill pt */
for(auto pair : pt)
{
  std::cout << pair.first << "," << pair.second.data() << std::endl;
}

For this json:

{
    "key1":"value1",
    "key2":"value2"
}

It outputs:

key1,value1
key2,value2
like image 1
Stewart Avatar answered Oct 24 '22 10:10

Stewart