Saturday, January 5, 2013

Traversing members of a JsonCpp's Json::Value object (2)

This morning I learned how to traverse the members of a Json::Value object using its iterators.
This is the same example I used in my previous post, but using iterators instead of the list of member names:
#include <iostream>
#include "jsoncpp/json.h"

using namespace std;

int main(int argc, char **argv)
{
  Json::Value change;
  Json::Value minParameters;
  Json::Value minParametersAnm;
 
  minParameters["MinimumRMS"] = 0.2;
  minParameters["sgbUpdated"] = true;
  change["Minimizer"] = minParameters;
  minParametersAnm["MinimumRMS"] = 0.5;
  minParametersAnm["sgbUpdated"] = false;
  change["Minimizer::ANM"] = minParametersAnm;
 
  cout<<"Traverse members of: "<<endl
    <<"\"change\":"<<endl
    <<change.toStyledString()<<endl<<endl;
 
  Json::Value::iterator it = change.begin();
 
  cout<<"List of members:"<<endl;
  for(Json::Value::iterator it = change.begin(); it !=change.end(); ++it)
  {
    Json::Value key = it.key();
    Json::Value value = (*it);
    
    cout<<"Key: "<<key.toStyledString();
    cout<<"Value: "<<value.toStyledString();
  }
  return 0;
}
Note the use of the key() method to get the key of the Json::Value from the iterator. Also note how we need to dereferentiate the iterator to get the Json::Value from the iterator.

Ok, so, I compiled it doing:
 
g++ -o test_iterator_members test_iterator_members.cpp -ljson_linux-gcc-4.4.5_libmt
And I executed it and got this result:
 
Traverse members of: 
"change":
{
   "Minimizer" : {
      "MinimumRMS" : 0.20,
      "sgbUpdated" : true
   },
   "Minimizer::ANM" : {
      "MinimumRMS" : 0.50,
      "sgbUpdated" : false
   }
}


List of members:
Key: "Minimizer"
Value: {
   "MinimumRMS" : 0.20,
   "sgbUpdated" : true
}
Key: "Minimizer::ANM"
Value: {
   "MinimumRMS" : 0.50,
   "sgbUpdated" : false
}

No comments:

Post a Comment