我正在使用此代码添加到我现有的 JSON 文件中。然而,它完全覆盖了我的 JSON 文件,当我只想将另一个项目添加到我的 JSON 文件中的项目列表时,它只将一个 JSON 对象放入其中。我该如何解决这个问题?
Json::Value root;
root[h]["userM"] = m;
root[h]["userT"] = t;
root[h]["userF"] = f;
root[h]["userH"] = h;
root[h]["userD"] = d;
Json::StreamWriterBuilder builder;
std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter());
std::ofstream outputFileStream("messages.json");
writer-> write(root, &outputFileStream);
最佳答案
我的建议是
- 将文件加载到
Json::Value
- 添加或更改您想要的任何字段
- 用更新的
Json::Value
覆盖原始文件>
这样做是最不容易出错的方法,除非您有非常大的 Json
文件,否则它会很快起作用。
如何读入整个文件
这很简单!我们创建根目录,然后使用 >>>
运算符读入文件。
Json::Value readFile(std::istream& file) {
Json::Value root;
Json::Reader reader;
bool parsingSuccessful = reader.parse( file, root );
if(not parsingSuccessful) {
// Handle error case
}
return root;
}
参见 this documentation here了解更多信息
关于c++ - 写入现有的 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55581883/