Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONcpp iterate through a list within the object

Tags:

c++

json

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

like image 533
Quantico Avatar asked Dec 04 '22 05:12

Quantico


2 Answers

In c++11 its even simpler now:

for (auto itr : json["name"]) {
    string name = itr.asString();
    // ...
}
like image 85
Chris Sattinger Avatar answered Dec 25 '22 05:12

Chris Sattinger


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.
like image 42
Josh Kelley Avatar answered Dec 25 '22 06:12

Josh Kelley