0

I'm using JSONCPP to log messages I get on my server, but instead of appending a message, it replaces last message. This is the code I have: the ofstream and event are private members.

  //std::ofstream myfile;
  m_file.open ("messageLogs.json");
  //Json::Value event;
  Json::Value array(Json::arrayValue);
  array.append(Json::Value(1));
  array.append(Json::Value(1));

  m_event["messages"]["time"] = "19:22";
  m_event["messages"]["message"] = msg;

  //populate object with objects
  Json::StyledWriter writer;
  m_file << writer.write(m_event) << std::endl;
  m_file.close();
Dries Jans
  • 107
  • 1
  • 11

1 Answers1

1

You could load the file as a Json::Value object, and append it there. Note this code snippet requires the json to have an array as the top-level item in the file, e.g.:

messageLogs.json

[]

main.cpp

#include <iostream>
#include <fstream>
#include <json/json.h>

int main(int argc, char* argv[])
{   
    std::fstream m_file;
    m_file.open ("messageLogs.json", std::ios::in);

    Json::Reader reader;
    Json::Value json_obj;

    if(!reader.parse(m_file, json_obj, true))
    {
        // json file must contain an array
        std::cerr << "could not parse the json file" << std::endl;
        return -1;
    }

    m_file.close();

    Json::Value m_event;
    m_event["messages"]["time"] = "19:22";
    m_event["messages"]["message"] = "Some message";//msg;

    // append to json object
    json_obj.append(m_event);

    std::cout << json_obj.toStyledString() << std::endl;

    // write updated json object to file
    m_file.open("messageLogs.json", std::ios::out);
    m_file << json_obj.toStyledString() << std::endl;
    m_file.close();

    return 0;
}
JBaczuk
  • 13,886
  • 10
  • 58
  • 86