Installation
Download json.hpp (or the single-include json.hpp from the releases page) and add it to your include path. That's it — no CMake targets to link, no package manager required for basic use:
#include <nlohmann/json.hpp> using json = nlohmann::json;
If you use CMake and vcpkg or Conan, nlohmann_json is available in both package managers and can be linked as nlohmann_json::nlohmann_json.
Parsing a JSON string
std::string raw = R"({"name":"Ada","age":36,"active":true})";
json j = json::parse(raw);
std::string name = j["name"]; // "Ada"
int age = j["age"]; // 36
bool active = j["active"]; // true
json::parse() throws json::parse_error on invalid input. Always wrap it in a try/catch in production code.
Reading from a file
#include <fstream>
std::ifstream f("config.json");
json config = json::parse(f);
The stream overload reads directly from any std::istream — file, stringstream, or network stream.
Serialising to a JSON string
json payload = {
{"user", {{"name", "Ada"}, {"score", 98}}},
{"tags", {"cpp", "json"}}
};
std::string compact = payload.dump(); // one line
std::string pretty = payload.dump(2); // indent 2 spaces
dump() returns a std::string. Pass an integer indent to pretty-print.
Safe value access
// Returns default if key is absent — never throws
std::string city = j.value("city", "Unknown");
// Check before access
if (j.contains("email")) {
std::string email = j["email"];
}
operator[] on a missing key inserts a null and returns a reference, which is usually not what you want in a read-only context. Prefer .value() or .contains().
Iterating an array
json arr = json::parse(R"([{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}])");
for (const auto& item : arr) {
std::cout << item["name"].get<std::string>() << "\n";
}
Error handling
try {
json j = json::parse("not valid json");
} catch (const json::parse_error& e) {
std::cerr << "Parse error: " << e.what() << "\n";
// e.byte gives the byte offset of the error
} catch (const json::type_error& e) {
std::cerr << "Type error: " << e.what() << "\n";
}
The two most common exceptions are parse_error (malformed JSON) and type_error (trying to use a value as the wrong type, e.g. treating a string as an integer). Both derive from json::exception.
Type mapping
JSON null → nullptr, boolean → bool, integer → int/long/int64_t, float → double, string → std::string, array → std::vector<json>, object → std::map<std::string, json>. Use .get<T>() to explicitly convert to a C++ type.