Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access an JSON array with boost::property_tree?

Tags:

json

boost

{
    "menu": 
    {
        "foo": true,
        "bar": "true",
        "value": 102.3E+06,
        "popup": 
        [
            {"value": "New", "onclick": "CreateNewDoc()"},
            {"value": "Open", "onclick": "OpenDoc()"},
        ]
    }
}

How can I get the value of onclick?

like image 490
wyz365889 Avatar asked Jul 01 '11 09:07

wyz365889


1 Answers

Iterate through the children of the menu.popup node and extract the onclick values:

void print_onclick_values(const ptree& node)
{
    BOOST_FOREACH(const ptree::value_type& child,
                  node.get_child("menu.popup")) {
        std::cout
            << "onclick: "
            << child.second.get<std::string>("onclick")
            << "\n";
    }
}

The function prints:

onclick: CreateNewDoc()
onclick: OpenDoc()

N.B. Delete the trailing comma from the example:

{"value": "Open", "onclick": "OpenDoc()"},

You can't access specific children of the array using a single get<string>(path) or get_child(path) call. The manual says:

Depending on the path, the result at each level may not be completely determinate, i.e. if the same key appears multiple times, which child is chosen is not specified. This can lead to the path not being resolved even though there is a descendant with this path. Example:

a -> b -> c
  -> b

The path "a.b.c" will succeed if the resolution of "b" chooses the first such node, but fail if it chooses the second.

The elements of the JSON array all have the empty string as name. You can access the onclick value an array element with

void print_arbitrary_onclick_value(const ptree& node)
{
    std::cout << node.get<std::string>("menu.popup..onclick") << "\n";
}

but you don't know for which element the access of onclick is attempted.

like image 153
antonakos Avatar answered Oct 19 '22 21:10

antonakos