Search code examples
c++jsonjsoncpp

JsonCpp Writing back to the Json File


I have a Config file with following contents:

{
    "ip": "127.0.0.1",
    "heartbeat": "1",
    "ssl": "False",
    "log_severity": "debug",
    "port":"9999"
}    

I have used JsonCpp for reading the content of above config file. Reading the content of Config File works fine, but writing the content in the Config File fails. I have following code:

#include <json/json.h>
#include <json/writer.h>
#include <iostream>
#include <fstream>
int main()
{
    Json::Value root;   // will contains the root value after parsing.
    Json::Reader reader;
    Json::StyledStreamWriter writer;
    std::ifstream test("C://SomeFolder//lpa.config");
    bool parsingSuccessful = reader.parse( test, root );
    if ( !parsingSuccessful )
    {
        // report to the user the failure and their locations in the document.
        std::cout  << "Failed to parse configuration: "<< reader.getFormattedErrorMessages();
    }
    std::cout << root["heartbeat"] << std::endl;
    std::cout << root << std::endl;
    root["heartbeat"] = "60";
    std::ofstream test1("C://SomeFolder//lpa.config");
    writer.write(test1,root);
    std::cout << root << std::endl;
    return 0;
}

The code prints the correct output in console, however the Config File is empty when this code executes. How do I make this code work?


Solution

  • All you need to do is explicitly closing the input stream

    test.close(); // ADD THIS LINE
    std::ofstream test1("C://LogPointAgent//lpa.config");
    writer.write(test1,root);
    std::cout << root << std::endl;
    return 0;