How to write the edited .json back to the .json file #3737
-
I open the .json file, I edit it. Then, I want to write it back to the .json file. How do I do that? Here is what I tried:
The output is: But the .json file does not change. It remains with its old content: {} . I have tried without the .dump() function, so the code was:
But still the file remains the same, unchanged. I also tried using |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
Your problem has nothing to do with this library. Your usage of |
Beta Was this translation helpful? Give feedback.
-
There are several ways of replace the content of the same file, However apart from all the solutions, // read file content
std::ifstream input_file("members.json");
nlohmann::json file_json = nlohmann::json::parse(input_file);
input_file.close();
// adjust json
file_json["pi"] = 3.141;
// write file content
std::ofstream output_file("members.json");
std::string file_json_string = file_json.dump();
output_file.write(file_json_string.c_str(), file_json_string.size());
output_file.close(); |
Beta Was this translation helpful? Give feedback.
There are several ways of replace the content of the same file,
such as clearing the end-of-file error,
then relocating the output pointer to the beginning of the file to replace the original content.
However apart from all the solutions,
the simplest way is just to separate the read/write file process,
such as the example I provided below.