我必须将我的应用程序做的事情记录到一个json文件中。预计应用程序将持续数周,因此我希望增量地编写json文件。
目前,我正在手动编写json,但是有一些日志阅读器应用程序正在使用Jsoncpp lib,并且也应该使用Jsoncpp lib来记录日志。
但在手册和一些例子中,我没有找到任何类似的东西。它总是类似于:
Json::Value root;
// fill the json
ofstream mFile;
mFile.open(filename.c_str(), ios::trunc);
mFile << json_string;
mFile.close();这不是我想要的,因为它不必要地填满了内存。我想逐步做这件事..有什么建议?
发布于 2013-05-22 22:15:34
如果您可以切换到普通的JSON到JSON行,如How I can I lazily read multiple JSON objects from a file/stream in Python?中所述(感谢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 ...但它是有效的。希望这能有所帮助。
发布于 2015-02-15 03:47:49
我是jsoncpp的维护者。不幸的是,它不会以增量方式写入。它确实在不使用额外内存的情况下写入到流中,但这对您没有帮助。
https://stackoverflow.com/questions/16689318
复制相似问题