我已经尝试了太多的时间,从boost库访问json_reader ptree。
我有一个经常被封装的json文件:(伪json:)
"Foo": {
"nameofFoo:"foofoo"
"Bar": [{
"BarFoo":
{ BarFooDeep: {
BarFooDeepDeep: {
"BarFooValue1": 123
"BarFooValue2" : 456
}
}
}
"FooBar": [ {
"FooBarDeep" :[ {
FooBarDeepDeep:[ {
FooBarValue1: "ineedthis"
FooBarValue2: "andthis"
} ]
FooBarDeepDeep1:[ {
FooBarValue1: "ineedthis"
FooBarValue2: "andthis"
} ]
"FooBarDeep" :[ {
FooBarDeepDeep2:[ {
FooBarValue1: "ineedthis"
FooBarValue2: "andthis"
} ]
FooBarDeepDeep3:[ {
FooBarValue1: "ineedthis"
FooBarValue2: "andthis"
} ]
and so on .... won t complete this now...现在我只需要得到FooBarValue1和FooBarValue2 of all FooBar。
我知道ptree将数组与空的childs ("")放在一起。
我可以通过递归遍历所有的childs来访问所有的成员。
但是,难道没有更好的方法来获取特殊的价值吗?
ptree是如何找到工作的?我总是收到编译错误..。
ptree jsonPT;
read_json( JSON_PATH, jsonPT);
ptree::const_iterator myIT = jsonPT.find("FooBarValue1");
double mlat = boost::lexical_cast<int>(myIT->second.data());错误:从‘boost::property_tree::basic_ptree,std::basic_string >::assoc_iterator’转换为非标量类型‘boost::property_tree::basic_ptree,std::basic_string >::const_iterator’请求的ptree::const_iterator myIT = jsonPT.find("FooBarValue1");
有人能给我一个有用的提示如何访问这个ptree吗?!?
发布于 2015-05-07 19:24:01
find()用于按键检索子节点;它不搜索整个ptree。它返回一个assoc_iterator (或const_assoc_iterator),您可以通过父级的to_iterator()方法将其转换为iterator:
ptree::const_assoc_iterator assoc = jsonPT.find("FooBarValue1");
ptree::const_iterator myIT = jsonPT.to_iterator(assoc);要搜索ptree,您需要递归地迭代它:
struct Searcher {
struct Path { std::string const& key; Path const* prev; };
void operator()(ptree const& node, Path const* path = nullptr) const {
auto it = node.find("FooBarValue1");
if (it == node.not_found()) {
for (auto const& child : node) { // depth-first search
Path next{child.first, path};
(*this)(child.second, &next);
}
} else { // found "FooBarValue1"
double mlat = boost::lexical_cast<int>(myIT->second.data());
// ...
std::cout << "Mlat: " << mlat << std::endl;
std::cout << "Path (reversed): ";
for (Path const* p = path; p != nullptr; p = p->prev)
std::cout << p << ".";
std::cout << std::endl;
}
}
};
Searcher{}(jsonPT);编写递归遍历的替代方法是C++14泛型lambda,或者在C++11中使用std::function删除类型的具体lambda。
https://stackoverflow.com/questions/30105711
复制相似问题