I am parsing a JSON
structure which is similar as follows
{
"item1" : "value1"
"item2" : "value2"
// ...
"itemn" : {
"outernestedItem1" : {
"innerNestedItem1" : "valuen1"
"innerNestedItem2" : "valuen2"
}
// ....
"outernestedItemn" : {
"innerNestedItem1" : "valuen1"
"innerNestedItem2" : "valuen2"
}
}
}
The number of outer nested items is not fixed, so I was iterating using iterator from rapidjson, inner-nested objects variables are fixed, so I can get access to them using [].
const rapidjson::Value& itemn = document["itemn"];
for (rapidjson::Value::ConstMemberIterator itr = itemn.MemberBegin();
itr != itemn.MemberEnd(); ++itr)
{
rapidjson::StringBuffer sb;
rapidjson::Writer<rapidjson::StringBuffer> writer( sb );
itr->value.Accept(writer);
std::cout << sb["innerNestedItem1"].GetString();
std::cout << sb["innerNestedItem2"].GetString();
}
but [] is not allowed with sb(string buffer), any idea how can I do this?
Edit1: I did it in very inefficient way, but just sharing the solution, so it might help someone to come up with efficient solution.
const rapidjson::Value& itemn = document["itemn"];
for (rapidjson::Value::ConstMemberIterator itr = itemn.MemberBegin();
itr != itemn.MemberEnd(); ++itr)
{
rapidjson::StringBuffer sb;
rapidjson::Writer<rapidjson::StringBuffer> writer( sb );
itr->value.Accept(writer);
//changed from here onwards
rapidjson::Document for_outer_nested_item;
std::string temp = sb.GetString();
char buffer2[100000];
strcpy_s(buffer2, temp.c_str());
for_outer_nested_item.ParseInsitu(buffer2);
std::cout << executive_command["innerNestedItem1"].GetString() << std::endl;
std::cout << executive_command["innerNestedItem2"].GetString() << std::endl;
}
First, let me provide credit to MiloYip at this link
Second-- here's what I did for my project:
I think this is a pretty clean/efficient approach.