Skip to content

How to write the edited .json back to the .json file #3737

Answered by ichenglin
Basilisvirus asked this question in Q&A
Discussion options

You must be logged in to vote

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.

// 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_s…

Replies: 2 comments 4 replies

Comment options

You must be logged in to vote
2 replies
@Basilisvirus
Comment options

@gregmarr
Comment options

Comment options

You must be logged in to vote
2 replies
@Basilisvirus
Comment options

@ichenglin
Comment options

Answer selected by Basilisvirus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants