Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RapidJSON library getting a value inside an array by its index

Tags:

c++

json

c

{"hi": "hellow",
"first":
    {"next":[
            {"key":"important_value"}
        ]
    }

}

Accessing RapidJSON inside array:

this works: cout << "HI VALUE:" << variable["hi"].GetString() << endl; this will output: hellow as expected, the problem is to access inside values like if I want to get "Important_Value", I tried something like this: cout << "Key VALUE:" << variable["first"]["next"][0]["key"].GetString() << endl ; but this doesn't work, I want to be able to get the "important_value" by the first item of the array, and in this case it's the [0] that is causing error.

How do I do to get it by its index? I hope it's clear my explanation.

Thanks in advance.

like image 433
Grego Avatar asked Apr 06 '12 00:04

Grego


3 Answers

JSON

    {"hi": "hellow", "first":  {"next":[{"key":"important_value"}  ] } }

Code:

rapidjson::Document document;       

if (document.Parse<0>(json).HasParseError() == false)
{
    const Value& a = document["first"];

    const Value& b = a["next"];

    // rapidjson uses SizeType instead of size_t.
    for (rapidjson::SizeType i = 0; i < b.Size(); i++)
    {
        const Value& c = b[i];

        printf("%s \n",c["key"].GetString());
    }        
}

Will print important_value

like image 102
mola10 Avatar answered Nov 13 '22 00:11

mola10


[Update]

By clever work of contributors, RapidJSON can now disambiguate literal 0 from string. So the issue is no longer happens.

https://github.com/miloyip/rapidjson/issues/167


The problem, as mjean pointed out, the compiler is unable to determine whether it should call the object member accessor or the array element accessor, by literial 0:

GenericValue& operator[](const Ch* name)
GenericValue& operator[](SizeType index)

Using [0u] or [SizeType(0)] can workaround this.

Another way to cope with this problem is stop using overloaded version for operator[]. For example, using operator() for one type of access. Or using normal functions, e.g GetMember(), GetElement(). But I do not have preference on this right now. Other suggestions are welcome.

like image 43
Milo Yip Avatar answered Nov 13 '22 00:11

Milo Yip


I noticed this in the tutorial.cpp file;

// Note:
//int x = a[0].GetInt();         // Error: operator[ is ambiguous, as 0 also mean a null pointer of const char* type.
int y = a[SizeType(0)].GetInt(); // Cast to SizeType will work.
int z = a[0u].GetInt();          // This works too.

I didnt test it but you may want to try one of these;

variable["first"]["next"][0u]["key"].GetString()

variable["first"]["next"][SizeType(0)]["key"].GetString()

like image 3
mjean Avatar answered Nov 13 '22 01:11

mjean