Json parser in CINT

Hello.

I am looking for a json parser that can be loaded and used in cint sessions. Something that could read ints, floats, strings and arrays of those types.
Does anybody know of or use one ?

I did not found anything like that …

I was using jsoncpp library in my code, it is however compiled, but you can try use it in scripts as well. Here is the snippet which you can almost copy one-to-one (except the last function configureFromJson):

[code]#include <json/json.h>

bool jsonReadTStringKey(const Json::Value & jsondata, const char * key, TString & target)
{
if (jsondata.isMember(key))
{
target = jsondata[key].asCString();
std::cout << " + " << key << ": " << target.Data() << std::endl;
return true;
}
return false;
}

bool jsonReadIntKey(const Json::Value & jsondata, const char * key, size_t & target)
{
if (jsondata.isMember(key))
{
target = jsondata[key].asInt();
std::cout << " + " << key << ": " << target << std::endl;
return true;
}
return false;
}

bool jsonReadFloatKey(const Json::Value & jsondata, const char * key, float & target)
{
if (jsondata.isMember(key))
{
target = jsondata[key].asFloat();
std::cout << " + " << key << ": " << target << std::endl;
return true;
}
return false;
}

bool configureFromJson(const char * filename, const char * name)
{
std::ifstream ifs(filename);
if (!ifs.is_open())
return false;

std::cout << "  Found JSON config file for " << name << std::endl;
Json::Value ana, cfg, axis;
Json::Reader reader;

bool parsing_success = reader.parse(ifs, ana);

if (!parsing_success)
{
	std::cout << "  Parsing failed\n";
	return false;
}
else
	std::cout << "  Parsing successfull\n";

if (!ana.isMember(name))
{
	std::cout << "  No data for " << name << std::endl;
	return false;
}

cfg = ana[name];

const size_t axis_num = 5;
const char * axis_labels[axis_num] = { "x", "y", "z", "cx", "cy" };
AxisCfg * axis_ptrs[axis_num] = { &x, &y, &z, &cx, &cy };

for (uint i = 0; i < axis_num; ++i)
{
	if (!cfg.isMember(axis_labels[i]))
		continue;
		
	axis = cfg[axis_labels[i]];

	jsonReadTStringKey(axis, "title", axis_ptrs[i]->title);
	jsonReadTStringKey(axis, "label", axis_ptrs[i]->label);
	jsonReadIntKey(axis, "bins", axis_ptrs[i]->bins);
	jsonReadFloatKey(axis, "min", axis_ptrs[i]->min);
	jsonReadFloatKey(axis, "max", axis_ptrs[i]->max);
}

ifs.close();
return true;

}[/code]
You should also load library libjsoncpp:

or link your code against it.

Here is example of input file:

{ "PtYcm" : { "cx" : { "bins" : 1, "max" : 0.2 }, "cy" : { "bins" : 6 }, "z" : { "bbins" : 20 } }, "PcmCosThcm" : { "cx" : { "bins" : 1 }, "cy" : { "bins" : 4, "max": 1500.0 }, "z" : { "bbins" : 20 } }, "XcmPcm" : { "cx" : { "bbins" : 3 }, "cy" : { "bbins" : 4 }, "z" : { "bbins" : 20 } } }

Jsoncpp is a bit fraky about syntax, specially there cannot be comma not followed by any key: value pair (python is much nicer about it).
So this is invalid entry

{ "key1": 10, "key2": 20, }
but this is valid

{ "key1": 10, "key2": 20 }