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开发者_JAVA技巧,\"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 I want to get the value of language1.
First of all, I've got to ask why you have a list with such different elements in it? If language1
has some special meaning, then I would split the data up into study
and study1
or something like that. In general, lists should be of a single type.
Assuming you can't change the format, here is the answer to your question. To the best of my knowledge, the only way to get something out of an array is to iterate over 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 over everything in the "study" list and looks for an entry with a "language1" key, printing the result
精彩评论