Search code examples
c++rapidjson

arrays of arrays writing to a file using rapidjson


Using below function I am writing vector of vector into a file and getting this:

[[[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3]]]

However I want the output to look like this:

[[1, 2, 3],[1, 2, 3],[1, 2, 3],[1, 2, 3]]

Code:

void resultToJson(std::vector<std::vector<int>> &result, const char *fileName) {
  rapidjson::Document d;
  rapidjson::Document::AllocatorType &allocator = d.GetAllocator();

  rapidjson::Value globalArray(rapidjson::kArrayType);
  std::vector<std::vector<int>>::iterator row;
  for (row = result.begin(); row != result.end(); row++) {
    std::vector<int>::iterator col;
    rapidjson::Value myArray(rapidjson::kArrayType);
    for (col = row->begin(); col != row->end(); col++) {
      myArray.PushBack(*col, allocator);
    }
    globalArray.PushBack(myArray, allocator);
  }
  d.SetArray().PushBack(globalArray, allocator);

  rapidjson::StringBuffer buffer;
  rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
  d.Accept(writer);

  std::ofstream of(fileName);
  of << buffer.GetString();
  if (!of.good())
    throw std::runtime_error("Can't write the JSON string to the file!");
}

I couldn't find out a way to do this. Any help would be appreciated.


Solution

  • You have globalArray to which you push a single element. It is not needed.

    Eliminating it and using d.SetArray().PushBack(myArray, allocator); instead should work just fine, and avoid creation of an extra level in the JSON tree.