问题描述
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;
现在我想要得到LANGUAGE1的价值。
Now I want to get the value of language1.
推荐答案
首先,我必须问,为什么你有它这样的不同元素的列表?如果 LANGUAGE1
有一些特殊的意义,那么我会拆分数据到研究
和研究1
或类似的东西。在一般情况下,列表应该是单一类型的
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;
}
}
这code在迭代都在研究的清单,并寻找一个LANGUAGE1键条目,打印结果
This code iterates over everything in the "study" list and looks for an entry with a "language1" key, printing the result
这篇关于如何访问一个JSON数组的boost :: property_tree?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!