简体   繁体   English

jsoncpp逐步写入

[英]jsoncpp write incrementally

I have to log down what my application does into a json file. 我必须将我的应用程序记录到json文件中。 Is expected that the application goes on for weeks and so I want to write the json file incrementally. 预计应用程序会持续数周,所以我想逐步编写json文件。

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. 目前我正在手动编写json,但是有一些日志阅读器应用程序正在使用Jsoncpp lib,并且应该很好地用Jsoncpp lib写下日志。

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? 我想逐步做...有些建议吗?

I am a maintainer of jsoncpp . 我是jsoncpp的维护者 Unfortunately, it does not write incrementally. 不幸的是,它没有逐步写入。 It does write into a stream without using extra memory, but that doesn't help you. 不使用额外内存的情况下写入流,但这对您没有帮助。

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? 如果你可以切换到普通的JSONJSON行 ,如我怎么能懒惰地从Python中的文件/流中读取多个JSON对象? (thanks ctn for the link), you can do something like that : (感谢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;  
}    

In this case, you do not have a single JSON in the file anymore... but it works. 在这种情况下,文件中没有单个JSON ......但它可以工作。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM