I have a C++ program where I jump around between many different files and classes collecting data that I'd like to output as one clean JSON file.
I'm using nlohmann's JSON files.
I can successfully write to a JSON file by doing the following:
json dm;
to_json(dm);
std::ofstream o("data_model.json");
o << setw(1) << dm << "\n";
void World::to_json(json& dm) {
dm = {
{"People", {
{"Rick", "c137"},
{"Jerry", "N/A"}
}}};
}
data_model.json then looks like:
{
"People": {
"Jerry": "N/A",
"Rick": "c137"
}
}
This is what a want, so far so good!
However, I seem to be unable to then pass "dm" to another function and append to the JSON file; it seems I can only write to the JSON file once.
To get around this, I'm trying to instead write all my desired data to a regular txt file, then somehow copy the data over from the text file into the JSON file in one go.
This is a sample of how I've tried to do that:
const char* fname = "text.txt";
// Writing to text file to later read from:
std::ofstream txt_for_jsn;
txt_for_jsn.open(fname);
txt_for_jsn <<
"{\n" <<
"{\"People\": {\n" <<
"\"Rick\": \"c137\"\n" <<
"\"Jerry\": \"N/A\"\n" <<
"}}};";
txt_for_jsn.close();
// Appending all lines from txt file to one string:
string txt_to_str;
std::ifstream read_file(fname);
string line;
while(std::getline(read_file, line)){
txt_to_str.append(line);
}
// Assigning the string that contains all of the txt file to the JSON file
dm = txt_to_str;
However, this doesn't give the same desired output as before. Instead, I get this:
"{{\"People\": {\"Rick\": \"c137\"\"Jerry\": \"N/A\"}}};"
Is there a better way to get my widely spread data consolidated nicely into a JSON file?