Showing posts with label JSON. Show all posts
Showing posts with label JSON. Show all posts

Wednesday, January 16, 2013

How to access the first element of an Json::Value array

To access the first element of an Json::Value array the following code may not work:
...
double x = point[0].asDouble()
...
Instead you have to write:
...
double x = point[0u].asDouble()
...
To find out why just check the following fragment of the Json::Value documentation:
const Value & operator[] (int index) const
Access an array element (zero based index)
You may need to say 'value[0u]' to get your compiler to distinguish this from the operator[] which takes a string.

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
}

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.

Wednesday, January 2, 2013

How to create a nested JsonCpp's Json::Value object

I needed to create a nested JsonCpp's Json::Value object.

This task is very easy using Json::Value's implicit constructors.

In the following example I created on the fly the configuration for a Minimizer object I wanted to include in a simulation:
#include <iostream>
#include "jsoncpp/json.h"

using namespace std;

int main(int argc, char **argv)
{
 // Creation
 Json::Value minimizer;
 Json::Value minParameters;
 minParameters["MinimumRMS"] = 0.2;
 minParameters["sgbUpdated"] = true;
 minimizer["Minimizer"]["parameters"] = minParameters;
 minimizer["algorithm"] = "TruncatedNewton";
 
 // Output to see the result
 cout<<"creating nested Json::Value Example pretty print: "
     <<endl<<minimizer.toStyledString()
     <<endl;
 
 return 0;
}
Compile it doing:
 
$ g++ -o test_create_json test_create_json.cpp -ljson_linux-gcc-4.4.5_libmt
And you'll get:
 
$ ./test_create_json 
creating nested Json::Value Example pretty print: 
{
   "Minimizer" : {
      "parameters" : {
         "MinimumRMS" : 0.20,
         "sgbUpdated" : true
      }
   },
   "algorithm" : "TruncatedNewton"
}

Tuesday, June 7, 2011

How to install JsonCpp in Ubuntu and use it in Eclipse CDT

You need to follow these instructions (I slightly modified this installing guide for Mac OS X) to install JsonCpp in Ubuntu and use it from Eclipse:

1. Download JsonCpp from here.

2. Create a new folder decompress and extract JsonCpp there:
$ mkdir /home/youruser/JsonCpp
$ tar xzf /home/youruser/JsonCpp/jsoncpp-src-0.5.0.tar.gz

3. Donwload the SCONS software construction tool from here and decompress and extract it in the jsoncpp-src-0.5.0 folder.
$ tar xzf /home/youruser/JsonCpp/jsoncpp-src-0.5.0/scons-local-1.3.0.tar.gz

4. Copy the contents of scons-local-1.3.0 inside jsoncpp-src-0.5.0

5. Go to jsoncpp-src-0.5.0 and build JsonCpp using SCONS:
$ cd /home/youruser/JsonCpp/jsoncpp-src-0.5.0
$ python scons.py platform=linux-gcc check

5. Install the JsonCpp library and header files:
$ sudo cp /home/youruser/JsonCpp/jsoncpp-src-0.5.0/libs/linux-gcc-4.4.5/libjson_linux-gcc-4.4.5_libmt.so /usr/lib
$ sudo mkdir /usr/include/jsoncpp
$ sudo cp /home/youruser/JsonCpp/jsoncpp-src-0.5.0/include/json/* /usr/include/jsoncpp/

6. Finally open your Eclipse project, go to Project -> Properties -> C/C++ Build -> Settings -> GCC C++ Linker -> libraries and add json_linux-gcc-4.4.5_libmt.

That's all you need to start using JsonCpp in Eclipse

Monday, June 6, 2011

Using JsonCpp to parse JSON in C++

We are using JSON (JavaScript Object Notation) to write the configuration files for our simulations.

JSON is a lightweight data-interchange format. The good thing is that JSON is easy for humans to read and write and that you can find good C++ libraries that parse and write it.

We're using one of them: JsonCpp.

There were several other C++ libraries listed in the JSON project website, but JsonCpp's documentation convinced me to use it.

I installed JsonCpp as a shared library (I'll soon post here how to do it in Linux and MacOs) and wrote a tiny example to test it:

#include <cstdio>
#include <cstring>

// This is the JSON header
#include "jsoncpp/json.h"

using namespace std;

int main(int argc, char **argv)
{
 string json_example = "{\"array\": \
                            [\"item1\", \
                            \"item2\"], \
                            \"not an array\": \
                            \"asdf\" \
                         }";

 // Let's parse it  
 Json::Value root;
 Json::Reader reader;
 bool parsedSuccess = reader.parse(json_example, 
                                   root, 
                                   false);
  
 if(not parsedSuccess)
 {
   // Report failures and their locations 
   // in the document.
   cout<<"Failed to parse JSON"<<endl 
       <<reader.getFormatedErrorMessages()
       <<endl;
   return 1;
 }
  
 // Let's extract the array contained 
 // in the root object
 const Json::Value array = root["array"];
 
 // Iterate over sequence elements and 
 // print its values
 for(unsigned int index=0; index<array.size(); 
     ++index)  
 {  
   cout<<"Element " 
       <<index 
       <<" in array: "
       <<array[index].asString()
       <<endl;
 }
  
 // Lets extract the not array element 
 // contained in the root object and 
 // print its value
 const Json::Value notAnArray = 
               root["not an array"];
 
 if(not notAnArray.isNull())
 {
   cout<<"Not an array: "
       <<notAnArray.asString()
       <<endl;
 }
 
 // If we want to print JSON is as easy as doing:
 cout<<"Json Example pretty print: "
     <<endl<<root.toStyledString()
     <<endl;
 
 return 0;
}

And this is the output:
$ g++ -o test_json test_json.cpp -ljson_linux-gcc-4.4.5_libmt
$ ./test_json 
Element 0 in array: item1
Element 1 in array: item2
Not an array: "asdf"

Json Example pretty print: 
{
   "array" : [ "item1", "item2" ],
   "not an array" : "asdf"
}

There are many other useful methods in JsonCpp's API.

Using a library like JsonCpp, we avoided all the parsing and could focus only on how to use the configuration data. This saved us a lot of time.