Introduction
nlohmann/json provides first-class JSON support for modern C++ without sacrificing type safety or readability. It maps JSON types directly to STL containers, making serialization and deserialization feel native to the language.
What nlohmann/json Does
- Parses JSON from strings, streams, or files into a strongly-typed
jsonobject - Serializes C++ structs and containers to JSON with user-defined
to_json/from_json - Supports JSON Pointer (RFC 6901), JSON Patch (RFC 6902), and JSON Merge Patch (RFC 7386)
- Provides SAX-style streaming for large documents that do not fit in memory
- Handles BSON, CBOR, MessagePack, and UBJSON binary formats
Architecture Overview
The library is a single header file (json.hpp, ~24 000 lines after preprocessing). Internally it uses a discriminated union (nlohmann::basic_json) backed by std::string, double, int64_t, bool, std::vector, and std::map. Template ADL hooks (adl_serializer) let users register custom types without modifying the library.
Self-Hosting & Configuration
- Header-only — drop
json.hppinto any include path; no build step required - CMake integration via
find_package(nlohmann_json)orFetchContent - Available on vcpkg, Conan, Homebrew, and most Linux package managers
- Compile-time switches:
JSON_DIAGNOSTICSfor better exception messages,JSON_NO_IOto strip stream operators - Minimum requirement: any C++11 compiler (GCC 4.8+, Clang 3.4+, MSVC 2015+)
Key Features
- Intuitive STL-like syntax:
j["key"], range-for, iterators - Automatic type deduction and implicit conversions
- Comprehensive RFC compliance (RFC 8259) with strict or relaxed parsing modes
- Extensive test suite with over 40 000 unit tests and continuous fuzzing
- MIT licensed with no external dependencies
Comparison with Similar Tools
- RapidJSON — faster parsing but lower-level API and manual memory management
- simdjson — read-only, SIMD-accelerated; best when you only need to parse
- Boost.JSON — part of Boost; heavier dependency chain
- cJSON — pure C, minimal footprint, no modern C++ features
- Glaze — newer, focuses on compile-time reflection for maximum speed
FAQ
Q: Is nlohmann/json fast enough for production? A: For most applications, yes. If you need absolute peak parsing speed, consider simdjson for reads and nlohmann/json for writes and manipulation.
Q: Can I serialize my own structs?
A: Yes. Define to_json and from_json free functions or use the NLOHMANN_DEFINE_TYPE_INTRUSIVE macro for automatic binding.
Q: Does it support comments in JSON files?
A: The default parser rejects comments per RFC 8259. Enable json::parse(input, nullptr, true, true) for relaxed parsing that ignores comments.
Q: How large is the compiled binary overhead?
A: Typically 200-400 KB depending on which features are instantiated. Using json_fwd.hpp for forward declarations reduces header inclusion costs.