How do I access an JSON array with boost::property_tree? -
int main(int argc, char *argv[]) { qcoreapplication a(argc, argv); // string s = "{\"age\":23,\"study\":{\"language\":{\"one\":\"chinese\",\"subject\":[{\"one\":\"china\"},{\"two\":\"eglish\"}]}}}"; string s = "{\"age\" : 26,\"person\":[{\"id\":1,\"study\":[{\"language\":\"chinese\"},{\"language1\":\"chinese1\"}],\"name\":\"chen\"},{\"id\":2,\"name\":\"zhang\"}],\"name\" : \"huchao\"}"; ptree pt; stringstream stream(s); read_json<ptree>( stream, pt); int s1=pt.get<int>("age"); cout<<s1<<endl; string s2 = pt.get<string>("person."".study."".language1"); cout<<s2<<endl;
now want value of language1.
first of all, i've got ask why have list such different elements in it? if language1
has special meaning, split data study
, study1
or that. in general, lists should of single type.
assuming can't change format, here answer question. best of knowledge, way out of array iterate on it.
#include <boost/foreach.hpp> boost_foreach(const ptree::value_type& val, pt.get_child("person.study")) { boost::optional<string> language1option = v.second.get_optional<string>("language1"); if(language1option) { cout<<"found language1: "<<*language1option<<endl; } }
this code iterates on in "study" list , looks entry "language1" key, printing result
Comments
Post a Comment