This is my json:
{
"data": {
"text": "hey stackoverflow",
"array_1": [
["hello", "world", 11, 14]
]
},
}
I have managed to extract the text
attribute like so:
Code:
document.Parse(request_body);
auto& data = document["data"];
std::string text = data["text"].GetString();
printf("text: %s\n", text.c_str());
Output:
text: hey stackoverflow
Now i need to extract array_1
as a std::vector<std::vector<std::any>>
.
I guess that, to have such a data type, i will have to iterate through data["array_1"]
using rapidjson's types to fill vectors.
The problem is that even after trying to replicate what i saw on the internet, i'm still unable to read the values inside data["array_1"]
.
Code:
auto& array_1 = data["array_1"];
static const char* kTypeNames[] = { "Null", "False", "True", "Object", "Array", "String", "Number" };
for (rapidjson::Value::ConstValueIterator itr = array_1.Begin(); itr != array_1.End(); ++itr){
printf("item\n");
for (rapidjson::Value::ConstValueIterator itr2 = itr->Begin(); itr2 != itr->End(); ++itr2){
printf("Type is %s\n", kTypeNames[itr->GetType()]);
}
}
Output:
item
Type is Array
Type is Array
Type is Array
Type is Array
But i need to have:
item
Type is String
Type is String
Type is Number
Type is Number
I was calling the GetType
on the wrong iterator..
Thanks for the help
printf("Type is %s\n", kTypeNames[itr2->GetType()]);
not
printf("Type is %s\n", kTypeNames[itr->GetType()]);
you are printing out the type of the item
, aka ["hello", "world", 11, 14]
, not the elements of ["hello", "world", 11, 14]
repeatedly.
Alternatively:
for (auto&& item : array_1.GetArray()) {
printf("item\n");
for (auto&& elem : item.GetArray()){
printf("Type is %s\n", kTypeNames[elem.GetType()]);
}
}
to get rid of some iteration noise. (Requires c++11 and rapidJson v1.1.0)