如何使用boost :: property_tree访问JSON数组? [英] 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()"},
]
}
}
如何获取onclick的价值?
遍历menu.popup
节点的子代并提取onclick
值:
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";
}
}
函数打印:
onclick: CreateNewDoc()
onclick: OpenDoc()
从示例中删除结尾的逗号:
{"value": "Open", "onclick": "OpenDoc()"},
您不能使用单个get<string>(path)
或get_child(path)
调用来访问数组的特定子级. 手册说 :
根据路径,每个级别的结果可能无法完全确定,即,如果同一键多次出现,则不会指定选择哪个子级.即使存在该路径的后代,这也可能导致该路径无法解析.示例:
a -> b -> c
-> b
如果解析度"b"选择第一个这样的节点,则路径"a.b.c"将成功,但是如果选择第二个则失败.
JSON数组的元素都具有空字符串作为名称.您可以使用
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";
}
}
值访问数组元素
void print_arbitrary_onclick_value(const ptree& node)
{
std::cout << node.get<std::string>("menu.popup..onclick") << "\n";
}
,但是您不知道尝试访问onclick
的哪个元素.
{
"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.
这篇关于如何使用boost :: property_tree访问JSON数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!