How to Parse JSON in C++
C++ has no standard JSON parser, but nlohmann/json (a single header) is the most popular choice. Parse with json::parse and serialize with dump.
Parse a JSON string
Include the header and call json::parse. Access values by key with type conversion.
cpp
#include <nlohmann/json.hpp>
using json = nlohmann::json;
json data = json::parse(text);
std::string name = data["name"];
std::string first = data["roles"][0];Serialize and pretty-print
dump() returns compact JSON; pass an indent width to pretty-print.
cpp
json obj = { {"name", "Ada"}, {"active", true} };
std::string compact = obj.dump(); // {"active":true,"name":"Ada"}
std::string pretty = obj.dump(2); // 2-space indentationHandle parse errors
Invalid JSON throws json::parse_error. You can also parse without exceptions.
cpp
try {
json data = json::parse(text);
} catch (const json::parse_error& e) {
std::cerr << "Invalid JSON: " << e.what() << "\n";
}