Friday, January 4, 2013

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

Today I needed to traverse the members of a Json::Value object.

After having a quick look at the documentation, I found the getMemberNames method, which returns a list with the member names, and did this little experiment:
#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;
 
  Json::Value::Members memberNames = change.getMemberNames();

  cout<<"Traverse members of: "<<endl
    <<"\"change\":"<<endl
    <<change.toStyledString()<<endl<<endl;
 
  cout<<"List of members:"<<endl;
  for(unsigned int i=0; i<memberNames.size(); ++i)
  {
    string memberName = memberNames[i];
    Json::Value value = change[memberName];
    cout<<"Key: "<<memberName<<endl;
    cout<<"Value: "<<value.toStyledString()<<endl;
  }
  return 0;
}
I compiled it:
 
g++ -o test_traverse_members test_traverse_members.cpp -ljson_linux-gcc-4.4.5_libmt
And this is what I got:
 
$ ./test_traverse_members 
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
}
We could get the same result using Json::value's iterators.
This will be material for a future post, though.

No comments:

Post a Comment