Reading a JSON file into ROOT C++

Hi Javier,

Thanks for your answer.

I had a look in the forum before I posted my message and I did not find a good answer.

The funny thing for me is that the nlohmann json code for C++ was included in ROOT at least in some releases (here). But I don’t know if it can be used (and, if so, how) any more.

I don’t understand either how to use the TBufferJSON class myself (even if that involves creating a TObject derived class mimicking the json contents). Of course, given that my idea is to have simple json (actually a dictionary in the python sense) I could write a class and a reader, but I expected someone had already coded a generic reader given JSON is quite common.

Also, I failed with using TPython. I tried the following example:

File myjson.json

{
    "key1": "value1", 
    "key2": "value2"
}

File myjson.py

print('Creating class myjson...')

import json

class myjson:

    def __init__( self ):
        print('in myjson.__init__')

    def load( self ):
        print('In myjson.load')
        with open('myjson.json') as f: 
            self._json=json.load(f)

    def getdata( self ):
        return self._json

    def printdata( self ):
        print(self._json)

    def getdata( self, key):
        return self._json[key]

Then I try in interactive mode (could not get it to work in a macro)

root [0]   TPython::LoadMacro( "myjson.py" );
Creating class myjson...
root [1]   myjson mj;
in myjson.__init__
root [2]   mj.load();
**ROOT_prompt_2:1:9: error: too few arguments to function call, single argument 'a0' was not specified**
**mj.load();**
**~~~~~~~ ^**
**input_line_16:15:2: note: 'load' declared here**
** TPyReturn load(const TPyArg& a0) {**
 **^**
root [3]   std::string v1 = (char*) mj.getdata( "key1" );
Error in <TRint::HandleTermInput()>: std::logic_error caught: basic_string::_M_construct null not valid
root [4]   std::cout << "Value for key1 is "  << v1 << std::endl;
Value for key1 is 

And those are all my ideas :pensive:.

Cheers,

Isidro