スポンサーリンク
nlohmann::jsonによる書き込みを行う。書き込み順は記述順と同じでなくなる点に注意。
#include <iostream> #include <nlohmann/json.hpp> #include <fstream> int main() { nlohmann::json jsondata;
jsondata["information"] = { {"Name", "Tarou"}, {"Age", 18}, {"weight", 60.5} }; nlohmann::json& data = jsondata["data"]; data["dates"].push_back("2023-10-01T12:00:00+09:00"); data["dates"].push_back("2023-10-02T12:00:00+09:00"); nlohmann::json countries = { {{"id", 1}, {"name", "Russia"}}, {{"id", 2}, {"name", "France"}} }; data["countries"] = countries;
// JSONデータをファイルに保存
std::string filename = R"(C:\test\data\data2.json)";
std::ofstream file(filename);
if (file.is_open()) {
file << jsondata.dump(2); // インデントのスペース数
file.close();
std::cout << "JSON data saved to " << filename << std::endl;
} else {
std::cerr << "Failed to open file for writing: " << filename << std::endl;
}
return 0;
}
{
"data": {
"countries": [
{
"id": 1,
"name": "Russia"
},
{
"id": 2,
"name": "France"
}
],
"dates": [
"2023-10-01T12:00:00+09:00",
"2023-10-02T12:00:00+09:00"
]
},
"information": {
"Age": 18,
"Name": "Tarou",
"weight": 60.5
}
}