0

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

EDIT

I was calling the GetType on the wrong iterator..

Thanks for the help

Community
  • 1
  • 1
lifeguru42
  • 156
  • 1
  • 12

1 Answers1

1
    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 and rapidJson v1.1.0)

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • Thank you very much, i wasn't paying attention on the basics so i did not saw that..so sry.. Thank you for the tip btw ! – lifeguru42 Oct 28 '19 at 17:17
  • i have c++17 and latest rapidjson version but i get a "no viable 'begin' function available" on the "for (auto&& item : array_1)". Thanks for your help anyway ! :D – lifeguru42 Oct 28 '19 at 17:31
  • @lifeguru42 Huh, I was quoting some docs. Aha: https://rapidjson.org/md_doc_tutorial.html I missed something -- need `.GetArray()`, probably because a json item could either be an array or an object, and iterating works differently on the two. – Yakk - Adam Nevraumont Oct 28 '19 at 18:11