I have to log down what my application does into a json file. Is expected that the application goes on for weeks and so I want to write the json file incrementally.
For the moment I'm writing the json manually, but there is some log-reader application that is using Jsoncpp lib and should be nice to write the log down with Jsoncpp lib too.
But in the manual and in some examples I haven't found anything similar.. It is always something like:
Json::Value root;
// fill the json
ofstream mFile;
mFile.open(filename.c_str(), ios::trunc);
mFile << json_string;
mFile.close();
That is not what I want because it unnecessary fills the memory. I want to do it incrementally.. Some advice?
If you can switch to plain JSON to JSON lines, as described in How I can I lazily read multiple JSON objects from a file/stream in Python? (thanks ctn for the link), you can do something like that :
const char* myfile = "foo.json";
// Write, in append mode, opening and closing the file at each write
{
Json::FastWriter l_writer;
for (int i=0; i<100; i++)
{
std::ofstream l_ofile(myfile, std::ios_base::out | std::ios_base::app);
Json::Value l_val;
l_val["somevalue"] = i;
l_ofile << l_writer.write(l_val);
l_ofile.close();
}
}
// Read the JSON lines
{
std::ifstream l_ifile(myfile);
Json::Reader l_reader;
Json::Value l_value;
std::string l_line;
while (std::getline(l_ifile, l_line))
if (l_reader.parse(l_line, l_value))
std::cout << l_value << std::endl;
}
In this case, you do not have a single JSON in the file anymore... but it works. Hope this helps.