0

I have a json-file

{
    "X": "3.5",
    "Y": "4.4"
}

and I need to change the value of the variable x (increase it by 0.5)

{
    "X": "4.0",
    "Y": "4.4"
}

I would like to read the file, change the variable and write the file. I have problems writing (modifying) a file.

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

int main(){
    std::string mConfigFileName = "./test.json";
    std::ifstream configFile(mConfigFileName);
    std::stringstream ss;
    ss << configFile.rdbuf();
    std::string configString = ss.str();

    Json::Value root;
    Json::Reader reader;
    bool ok = reader.parse(configString, root );
    double X = std::stod(root["X"].asString().c_str());
    std::cout << "X  = "<< X << std::endl;
    X += 0.5;
    // how to save changes ???
}


g++ -I/usr/include/jsoncpp/ test.cpp -ljsoncpp
  • Here are some examples that might help: https://stackoverflow.com/questions/4289986/jsoncpp-writing-to-files – schteppe Jul 14 '20 at 09:47
  • Thank! That's exactly what I did. But I do not like the fact that I completely rewrote the file. It seems to me that this is not effective: `readAllJson(); X+=0.5; writeAllJson();` – iprogger Jul 14 '20 at 09:59
  • No problem! I don’t think it’s possible to do it in any other way. But let me know if you find a way to do that :) – schteppe Jul 14 '20 at 10:32

0 Answers0