c++ - 写入现有的 json 文件

标签 c++ json jsoncpp

我正在使用此代码添加到我现有的 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/

相关文章:

linux - 无法使用 scons 在 redhat 中构建 jsoncpp 库

c++ - JsonCpp 在退出函数时抛出 LogicError

c++ - 无法解析在 0MQ 套接字中接收到的 Jsoncpp 对象

c++ - libclang 获取成员声明

c++ - 为什么 g++ 和 clang++ 之间的编译时间差异很大?

mysql - 乱码 : json of json not work

json - 有没有办法根据查询参数在响应中包含多个 json 文件?

android - 通过 https 发送和接收 json 消息

c++ - 使用 getline 在运行时获取与文件输入相关的错误

c++ - 需要一个简短、复杂的 C++ 代码和一个更长、易于理解的版本