boost::json How to serialize to file (std::ofstream) minimal example
#include <boost/json.hpp>
#include <fstream>
#include <iostream>
namespace json = boost::json;
int main() {
// Create a JSON object
json::object obj{
{"name", "John Doe"},
{"age", 30},
{"city", "New York"}
};
// Open the output file stream
std::ofstream file("output.json");
if (file.is_open()) {
// Serialize the JSON object and write it to the file
file << obj;
// Close the file stream
file.close();
std::cout << "JSON object serialized and written to file successfully." << std::endl;
} else {
std::cout << "Unable to open file for writing." << std::endl;
}
return 0;
}
Compile using:
g++ -o main main.cpp -lboost_json
After running the program using ./main
, output.json
will look this this:
{"name":"John Doe","age":30,"city":"New York"}