-
Hello! I am new and learning C++ for the first time and want to store data from my C++ application to a .json file and read the data again in C++. My example .json file: {
"Name1":
{
"Food":"Candy",
"Number":100
},
"Name2":
{
"Food":"Cake",
"Number":null
}
} How could I read the json file and store Name1's Food (Candy) as a string in C++? Along with the Name1's Number and Name2's items. And how could I write/edit the json file and save it? So that I can change Name1's Food to something like cookies? And last but not least, how could I delete a part of the json file in C++? For example, if I want to delete the Food id or the Name2. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Assuming your file is called // parse
std::ifstream i("data.json");
json j;
i >> j;
// read
std::string food = j["Name1"]["Food"];
// change
j["Name1"]["Food"] = "Cookie";
// delete
j.erase("Name1"); See https://github.com/nlohmann/json and https://json.nlohmann.me for more information. |
Beta Was this translation helpful? Give feedback.
-
Ah thank you @nlohmann , that solved my problem! Another problem I got working on my project was that when I try to delete something inside of something like for example deleting number inside of Name2 I found no way to do so. Another, (and hopefully last thing) is if your json.hpp has a function to delete the contents of a file, I ask this because when I save it, it writes next to the data that was previously there, I want to overwrite the data. If not is there a way to delete the contents of a file in C++? I have defined i as input and output using #include for reading AND writing. Your help is much appreciated! |
Beta Was this translation helpful? Give feedback.
Assuming your file is called
data.json
, this should work:See https://github.com/nlohmann/json and https://json.nlohmann.me for more information.