My json object has a list in it and I would like to iterate through the elements of the list I saw the following post Iterating through objects in JsonCpp , but this did not work for me
My json object:
{
"name": ["str1",str2" ... ]
}
The code that I have and is not working
Json::Value names= (*json)["name"];
for( Json::ValueIterator itr = names.begin() ; itr != names.end() ; itr++ ) {
string name = *itr.asString();}
I am getting the following error
cannot convert from 'Json::Value' to 'std::basic_string<_Elem,_Traits,_Ax>
I am sure the elements are string because calling string name = names= (*json)["name"][0].asString()
is working
In c++11 its even simpler now:
for (auto itr : json["name"]) {
string name = itr.asString();
// ...
}
I don't see how you can get a cannot convert
error from your code, but I do think I see the problem.
Json::ValueIterator
is an iterator; in other words, similar to a pointer, it needs to be dereferenced to access the value it points to.
itr.asString()
tries to access the asString
method of the iterator, and the iterator doesn't have an asString
method.*itr.asString()
tries to access the asString
method of the iterator then dereference the result (because of order of operations; .
has a higher precedence than *
), and the iterator doesn't have an asString
method.(*itr).asString()
(using parentheses to clarify precedence) or itr->asString()
(using the ->
operator, the preferred approach) should work.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