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"
}

7 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hi,
    Is there any way to not allow jsoncpp reoeder the entries on the basis of name ??

    ReplyDelete
  3. Hi,
    I am new in creating JSON objects using C++.

    is there any way to create json object dynamically ?

    I want to create below output JSON using JSONCPP.

    {
    "algorithm" : "TruncatedNewton",
    "Developer" : "XYZ",
    "SupportTeam" : "XYZ"
    },
    {
    "algorithm" : "Database",
    "Developer" : "ABC",
    "SupportTeam" : "ABC"
    }
    ...
    ...
    ...

    My output will be different every-time like sometime there should be 2 values or sometime there should be 3 or many...

    Can anyone help me how to achieve it using JSONCpp Json::Value?

    ReplyDelete
    Replies
    1. Hi,
      did you get the solution to print values in iteration?

      Delete
  4. Thank you for your post - it was very well easy to understand, and gave me the results I wanted.

    ReplyDelete