nlohmann/json Knowledge Base
nlohmann/json — formally "JSON for Modern C++" — is a
single-header, C++11 library that models JSON as an STL-like container. Assigning a std::string
into a json, iterating it with a range-for, comparing two documents with ==: all of it reads
like ordinary C++ rather than a bolted-on parsing API.
It is not the fastest JSON library in C++ — RapidJSON and simdjson both outrun it on raw parse throughput — but it became the de facto default anyway, because most code that touches JSON is bottlenecked on developer time, not parse time. These docs cover the library as you'll actually use it: parsing and building documents, accessing and iterating them safely, converting your own types, and the advanced corners (SAX, binary formats, numeric precision) you reach for once the easy path stops being enough.
Roughly outside-in: Overview → Basics get you parsing and printing JSON; Accessing & Modifying and Custom Type Conversion are the day-to-day work of reading fields and mapping them to your own structs; Advanced Features and Numbers, Memory & Performance are what you reach for when the easy path stops being enough — streaming parses, binary wire formats, precision and allocation control. Each folder is self-contained — follow the cross-links between pages.
Sections
| Section | What it covers | |
|---|---|---|
| Overview | What it is, installing it, design philosophy, how it compares to RapidJSON/simdjson | |
| Basics | Parsing, constructing values, the value type, dumping | |
| Accessing & Modifying | operator[] vs .at(), iteration, conversions, JSON Pointer/Patch | |
| Custom Type Conversion | to_json/from_json, the macros, adl_serializer | |
| Advanced Features | SAX parsing, CBOR/MessagePack/BSON, the exception hierarchy | |
| Numbers, Memory & Performance | Number storage and precision, basic_json template parameters, avoiding copies |
Suggested reading paths
- Just need to read a config file: Parsing → Element access → Error handling.
- Serializing your own structs: to_json/from_json → Macros → adl_serializer.
- It's too slow / too big: Comparison with alternatives → SAX interface → Performance.
Quick reference
#include <nlohmann/json.hpp>
using json = nlohmann::json;
json j = json::parse(R"({"name":"ada","age":36})"); // parse
std::string name = j.at("name"); // checked access
int age = j.value("age", 0); // access with default
j["tags"] = {"math", "engine"}; // assign an array
std::string out = j.dump(2); // pretty-print, 2-space indent
| Task | Call |
|---|---|
| Parse a string | json::parse(str) |
| Parse a stream | json j; ifs >> j; |
| Access, throwing | j.at("k") |
| Access, with default | j.value("k", fallback) |
| Type test | j.is_object(), j.is_null(), … |
| Convert out | j.get<T>() / j.get_to(x) |
| Serialize | j.dump() / j.dump(indent) |