Jsoncpp增量写入

jsoncpp write incrementally

本文关键字:Jsoncpp      更新时间:2023-10-16

我必须将我的应用程序的操作记录到json文件中。预计应用程序将持续数周,所以我想增量地编写json文件。

目前我正在手动编写json,但是有一些使用Jsoncpp库的日志阅读器应用程序,应该也可以使用Jsoncpp库编写日志。

但是在手册和一些例子中,我没有发现任何类似的东西。它总是像这样:

Json::Value root;
// fill the json
ofstream mFile;
mFile.open(filename.c_str(), ios::trunc);
mFile << json_string;
mFile.close();

这不是我想要的,因为它不必要地填充内存。我想循序渐进地做……一些建议吗?

我是jsoncpp的维护者。不幸的是,它不能增量地编写。它在不使用额外内存的情况下将写入流,但这对您没有帮助。

如果您可以切换到纯JSONJSON行,如我如何在Python中从文件/流中惰性读取多个JSON对象所述?(感谢ctn提供链接),您可以这样做:

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

在这种情况下,你不再有一个JSON文件了…但它是有效的。