Create an array of JSON strings using jsoncpp

I need to update the index (in JSON format) when writing a new file to disk, and since the files are classified, I use an object with this structure:

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

I thought this was an easy task for jsoncpp, but I probably missed something.

My code (simplified) is here:

 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; } 

So, I open the file, reading the JSON data, if I cannot find it, I create a new array, the problem is that when I try to add a value to the array, it does not work, the array remains empty and is written to the file.

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

Tried to debug my code and jsoncpp calls, and everything looks fine, but the array is always empty.

+6
source share
1 answer

This is where the problem arises:

 elements = root[type]; 

because when you call this JsonCpp API, you create a copy of root[type] :

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

thereby not modifying the root document at all. The easiest way to avoid this problem is to not use the elements variable in your case:

 root[type].append(name.c_str()); 
+5
source

Source: https://habr.com/ru/post/954157/


All Articles