c++jsonboostboost-propertytreeboost-foreach

How do we get objects in boost property tree


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.