How to Parse JSON in C++

← All guides

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 indentation

Handle 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";
}

Frequently Asked Questions

nlohmann/json is the most widely used for its intuitive API and header-only design. RapidJSON is faster for high-performance needs but has a lower-level API.

It's header-only — add the single json.hpp, or install via vcpkg, Conan, or your package manager, then #include <nlohmann/json.hpp>.

Define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, field1, field2) on your struct to enable automatic conversion to and from json.

Related Tools