How do I access an JSON array with boost::property_tree?
{
"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?
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.
精彩评论