I have been trying for too much time now, to access a json_reader ptree from the boost library.
I have a json file that is capsulated really often: (pseudo-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...
Now I only need to get FooBarValue1 and FooBarValue2 of all FooBar.
I know ptree puts arrays together with empty childs ("")
I can access all the members by itereration over all the childs recursively.
But is there not a better way to access special values?
how does ptree find works? i always get compiler errors ...
ptree jsonPT;
read_json( JSON_PATH, jsonPT);
ptree::const_iterator myIT = jsonPT.find("FooBarValue1");
double mlat = boost::lexical_cast<int>(myIT->second.data());
error: conversion from ‘boost::property_tree::basic_ptree, std::basic_string >::assoc_iterator’ to non-scalar type ‘boost::property_tree::basic_ptree, std::basic_string >::const_iterator’ requested ptree::const_iterator myIT = jsonPT.find("FooBarValue1");
Can anyone give me a useful hint how to get access to this ptree?!?
find()
is for retrieving a child node by key; it doesn't search the whole ptree. It returns anassoc_iterator
(orconst_assoc_iterator
), which you can convert to aniterator
via theto_iterator()
method on the parent:To search the ptree, you'll need to iterate it recursively:
Alternatives for writing the recursive traversal would be a C++14 generic lambda, or in C++11 a type-erased concrete lambda using
std::function
.As hinted in the linked answer I commented (Boost.PropertyTree subpath processing), you could write your own "selector" query, so you could write stuff like:
The
enumerate_path
function need not be too complicated and takes any output iterator (so you canback_inserter(some_vector)
just as well):As simple working demo prints:
That is with the following input.txt:
Live On Coliru
Full Listing
Live On Coliru