我有一个具有json对象数组的json文件。我正在使用RapidJSON C++。
我想将新对象附加到此文件内的json数组中
目前我正在做的是,我使用fileread流读取json对象中的整个文件,并使用先前读取的该文档数组内的AddMember添加新成员(新json对象)。现在我覆盖文件中的这个新对象,并对新对象重复该过程。
此解决方案不可扩展。有人可以指出使用RapidJSON或原始文件流的任何其他解决方案。帮助将不胜感激,我一直在互联网上寻找,但没有运气。
是否有类似使用json追加到文件的内容。
或其他任何可扩展的解决方案,因为我的文件大小会随着时间的流逝而变得非常大,因此每次读取整个文件,然后附加一个新对象然后重写整个文件将浪费内存和CPU时间。
请帮我这个
最佳答案
这个问题来自几年前,但是这个答案仍然有意义。
目标是将带有json
的rapidjson
对象附加到包含json
数组的可能已经存在的文件中。满足以下条件:
这是带有注释的代码:
bool appendToFile(const std::string& filename, const rapidjson::Document& document)
{
using namespace rapidjson;
// create file if it doesn't exist
if (FILE* fp = fopen(filename.c_str(), "r"); !fp)
{
if (fp = fopen(filename.c_str(), "w"); !fp)
return false;
fputs("[]", fp);
fclose(fp);
}
// add the document to the file
if (FILE* fp = fopen(filename.c_str(), "rb+"); fp)
{
// check if first is [
std::fseek(fp, 0, SEEK_SET);
if (getc(fp) != '[')
{
std::fclose(fp);
return false;
}
// is array empty?
bool isEmpty = false;
if (getc(fp) == ']')
isEmpty = true;
// check if last is ]
std::fseek(fp, -1, SEEK_END);
if (getc(fp) != ']')
{
std::fclose(fp);
return false;
}
// replace ] by ,
fseek(fp, -1, SEEK_END);
if (!isEmpty)
fputc(',', fp);
// append the document
char writeBuffer[65536];
FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
Writer<FileWriteStream> writer(os);
document.Accept(writer);
// close the array
std::fputc(']', fp);
fclose(fp);
return true;
}
return false;
}
关于c++ - RapidJSON C++将JSON对象附加到文件的高效且可扩展的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47440099/