Question

I was wondering if there where some convenient way to access a known index of a list using the path methodology.

My dream method

float v = pt.get<float>("root.list[0]);

Current known method (or something like it)

 ptree::value_type listElement;
 BOOST_FOREACH(listElement,tree.get_child("root.list")){
                return listElement.second.get<float>();
            }

Format of List (json)

{
root:{
 list:[1,2,3,4,5]
}
}
Was it helpful?

Solution

You should be able to access the range of elements in the list using boost::property_tree::equal_range. With the JSON you format you are using there is no name element associated with each item in the list. This means that it is necessary to get the parent node prior to accessing the child elements in the range.

The code below is a crude example that you could adapt:

Input Json File (in.json) :

{
    "root" :
    {
        "list" : [1,2,3,4,5]
    }
}

Function to print the nth element of the list:

void display_list_elem( const ptree& pt, unsigned idx )
{
    // note: the node elements have no name value, ergo we cannot get
    // them directly, therefor we must access the parent node,
    // and then get the children separately

    // access the list node
    BOOST_AUTO( listNode,  pt.get_child("root.list") );


    // get the children, i.e. the list elements
    std::pair< ptree::const_assoc_iterator,
               ptree::const_assoc_iterator > bounds = listNode.equal_range( "" );


    std::cout << "Size of list : " << std::distance( bounds.first, bounds.second ) << "\n";
    if ( idx > std::distance( bounds.first, bounds.second ) )
    {
        std::cerr << "ERROR Index too big\n";
        return;
    }
    else
    {
        std::advance( bounds.first, idx );

        std::cout << "Value @ idx[" << idx << "] = " 
                  << bounds.first->second.get_value<std::string>() << "\n";
    }

    std::cout << "Displaying bounds....\n";
    display_ptree( bounds.first->second, 10 );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top