使用 jsoncpp 创建字符串的 JSON 数组

Create JSON array of strings with jsoncpp

本文关键字:JSON 数组 字符串 jsoncpp 创建 使用      更新时间:2023-10-16

在将新文件写入磁盘时,我需要更新索引(JSON 格式),并且由于文件已分类,因此我使用的是具有这种结构的对象:

{ "type_1" : [ "file_1", "file_2" ], "type_2" : [ "file_3", "file_4" ] }

我认为这对jsoncpp来说很容易,但我可能错过了一些东西。

我的代码(简化)在这里:

std::ifstream idx_i(_index.c_str());
Json::Value root;
Json::Value elements;
if (!idx_i.good()) { // probably doesn't exist
    root[type] = elements = Json::arrayValue;
} else {
    Json::Reader reader;
    reader.parse(idx_i, root, false);
    elements = root[type];
    if (elements.isNull()) {
        root[type] = elements = Json::arrayValue;
    }
    idx_i.close();
}
elements.append(name.c_str()); // <--- HERE LIES THE PROBLEM!!!
std::ofstream idx_o(_index.c_str());
if (idx_o.good()) {
    idx_o << root;
    idx_o.close();
} else {
    Log_ERR << "I/O error, can't write index " << _index << std::endl;
}

所以,我打开文件,读取 JSON 数据有效,如果我找不到任何数据,我创建一个新数组,问题是:当我尝试将值附加到数组时,它不起作用,数组保持为空,并写入文件。

{ "type_1" : [], "type_2" : [] }

尝试调试我的代码和 jsoncpp 调用,一切似乎都很好,但数组始终为空。

问题出现在这里:

elements = root[type];

因为在调用此 JsonCpp API 时,您正在创建root[type]的副本

Value &Value::operator[]( const std::string &key )

因此根本不修改root文档。避免此问题的最简单方法是,在您的情况下,不使用 elements 变量:

root[type].append(name.c_str());