Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonCpp Writing back to the Json File

Tags:

c++

json

jsoncpp

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?

like image 859
Pant Avatar asked Dec 15 '14 14:12

Pant


2 Answers

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;
like image 89
Shmil The Cat Avatar answered Sep 28 '22 04:09

Shmil The Cat


All you need to do is close the opened file.

test1.close();

like image 38
prakhar3agrwal Avatar answered Sep 28 '22 06:09

prakhar3agrwal