{"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.
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
[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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With