作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在玩 boost::property_tree::ptree ,即使用以下 json file :
{
"menu":
{
"foo": "true",
"bar": "true",
"value": "102.3E+06",
"popup":
[
{
"value": "New",
"onclick": "CreateNewDoc()"
},
{
"value": "Open",
"onclick": "OpenDoc()"
}
]
}
}
到目前为止,我一直在尝试访问嵌套的“值”,但没有成功,这就是我所做的:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
int main(int argc, char *argv[])
{
const char *filename = argv[1];
using boost::property_tree::ptree;
ptree pt;
read_json(filename, pt);
std::string v0 = pt.get<std::string>("menu.value"); // ok
//std::string v1 = pt.get<std::string>("menu.popup.value"); // not ok
//std::string v2 = pt.get<std::string>("menu.popup.1.value"); // not ok
//std::string v3 = pt.get<std::string>("menu.popup.''.value"); // not ok
// ugly solution:
BOOST_FOREACH(ptree::value_type &v,
pt.get_child("menu.popup"))
{
const ptree &pt2 = v.second;
std::string s = pt2.get<std::string>("value");
}
return 0;
}
到目前为止,我所有的尝试都“不正常” 失败了。似乎 string_path 不允许访问整个 ptree,正如人们所想象的那样(想想 XML 世界中的 XPath)。还是我遗漏了什么?
最佳答案
属性树(从 1.54 开始)不支持数组。您可以看到 JSON ptree 序列化程序如何将 JSON 数组对象转换为合适的(未命名;key="")节点 here .
Ptree 的字符串路径通过键路径解析值(其中键名称由点分隔)。由于数组对象最终成为未命名的节点,因此如果不迭代根节点的子节点(在本例中为“弹出”),就无法访问各个节点。您可以阅读如何使用 various get() overloads here
Ptree's five minute example使用一个 XML 源,该源包含一个元素(“模块”)和一个子数组(每个元素都命名为“模块”)。就像您的情况一样,正确访问每一个的唯一方法是迭代 get_child() 的结果
关于c++ - 使用 boost::property_tree::string_path 访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18893642/
我正在玩 boost::property_tree::ptree ,即使用以下 json file : { "menu": { "foo": "true",
我是一名优秀的程序员,十分优秀!