About the JSON to C++
Generate a C++17 header with structs and from_json/to_json functions for the popular nlohmann/json library. Nullable and optional fields use std::optional and arrays use std::vector.
Key features
- C++17 header with structs for each JSON object
- from_json / to_json functions for nlohmann/json
- std::optional for nullable and optional fields
- std::vector for arrays, int64_t and double for numbers
- Value-initialized members ({}), so no garbage values
- Optional namespace; C++ keywords avoided
C++ structs for nlohmann/json
C++ has no built-in reflection, so mapping JSON to structs means writing serialization code by hand. Paste a sample and get a complete header: structs plus from_json/to_json functions for nlohmann/json.
Example
[
{ "user_id": 7, "name": "Ada", "nickname": "ada", "score": 4.5 },
{ "user_id": 8, "name": "Alan", "nickname": null, "score": 3 }
]
struct User {
int64_t user_id{};
std::string name{};
std::optional<std::string> nickname{};
double score{};
};
inline void from_json(const nlohmann::json& j, User& x) {
j.at("user_id").get_to(x.user_id);
j.at("name").get_to(x.name);
if (j.contains("nickname") && !j.at("nickname").is_null()) x.nickname = j.at("nickname").get<std::string>();
j.at("score").get_to(x.score);
}
auto users = nlohmann::json::parse(text).get<std::vector<User>>();
Type mapping
| JSON | C++ |
|---|---|
"text" | std::string |
42 | int64_t |
3.14 | double |
true | bool |
[...] | std::vector<T> |
{...} | struct |
| null or missing | std::optional<T> |
| unknown | nlohmann::json |
Tips
- Errors:
j.at()throwsnlohmann::json::out_of_rangewhen a required key is missing, so wrap parsing intry/catch. - Performance: for very large documents, consider the SAX interface or simdjson for read-only access.
- Header-only: everything is
inline, so the header can be included from multiple translation units.
Related tools
Prefer Rust? Use JSON to Rust. Need a schema for gRPC? Try JSON to Protobuf.
How to use the JSON to C++
- Paste your data into the input box, upload a file, or click Sample to try it out.
- Adjust the options above the editor if you need to (indentation, delimiter, and so on).
- The C++ appears instantly in the output panel. Any errors are shown with their line and column.
- Click Copy to copy the result, or Download to save it as a file.