Files
json/docs/mkdocs/docs/integration/cmake.md
T
Niels Lohmann a47170346a docs: new design for the documentation site (#5934)
* docs: new design for the documentation site

Apply the brand to the Material for MkDocs site: Inter and JetBrains Mono
served by the site (upright and real italic), brand colours, blue header band
with the syntax pattern, wordmark in the header, new home page (hero, cards,
animated feature tour), 404 page, polish for tabs, search, footer, focus
rings, tables and code blocks, and theme features (code copy, previous/next
footer, TOC follow, search suggestions).

Draw the number railroad diagram, the parser callback events and the iterator
illustrations as inline SVGs that follow the light and dark scheme. The
generator scripts are in docs/mkdocs/scripts/figures; the feature slideshow
(json-light.svg, json-dark.svg, replacing json.gif on the home page) is built
by docs/mkdocs/scripts/slideshow. Decision nodes in five flowcharts become
hexagons, which need far less room.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* docs: add figures, table captions and a macro chooser

- Figures with numbered captions: SAX stepper, json_view layout and edit
  stepper, exception map, JSON pointer and patch walkers, QA pipeline,
  scaling and binary size charts, roadmap lanes, release timeline,
  integration decision tree and namespace builder
- Table captions (nj-table-caption) on 9 pages
- Compile times: modules and PCH charts, filesystem section, re-measured
  Figure 1, links between features/modules.md and compile_times.md
- Interactive macro chooser for features/arbitrary_types.md
- Link check: exclude URLs that answer the plugin with 400/401/419 or are
  dead (customers.md)

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* docs: macro chooser generates adl_serializer for non-default-constructible types

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* docs: cross-link concept pages and API pages in See also sections

Add See also links in both directions between the concept pages (features,
home, integration) and the API pages, write API links in code font, give every
entry a comment after a dash, and show the callback event figure on the parser
callbacks page.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

* docs: address review comments on the new design

- Home: add a "Latest release" button
- Sponsors: update the list and group it by tier
- Features: list all feature pages on the index page
- Releases: add highlights per release, link the 4.0 roadmap, add the first commit to the timeline
- Exceptions: prefix all example messages with the exception name
- API: no code font for format names in the See also links of the to_/from_ pages
- Merge Patch: show the document before, the patch, and the result
- Replace "--" with typographic dashes, mark external links with an icon, center Mermaid diagrams

Signed-off-by: Niels Lohmann <mail@nlohmann.me>

---------

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-27 07:41:42 +01:00

12 KiB

CMake

Integration

You can use the nlohmann_json::nlohmann_json interface target in CMake. This target populates the appropriate usage requirements for INTERFACE_INCLUDE_DIRECTORIES to point to the appropriate include directories and INTERFACE_COMPILE_FEATURES for the necessary C++11 flags. Most package managers that provide a CMake package configuration for this library expose this same target.

All ways of adding the library described below end at this one target:

flowchart LR
    FP["<b>find_package()</b><br>installed package"] --> T
    AS["<b>add_subdirectory()</b><br>embedded source tree"] --> T
    FC["<b>FetchContent</b><br>downloaded at configure time"] --> T
    PM["<b>Package manager</b><br>its CMake package"] --> T
    T["<b>nlohmann_json::nlohmann_json</b><br>one INTERFACE target"] --> L["<b>target_link_libraries()</b><br>link it PRIVATE"]

The four ways to add the library in CMake all lead to the same `nlohmann_json::nlohmann_json` interface target, which a project links with `target_link_libraries`. The CMake options below apply to `add_subdirectory()` and `FetchContent`; installed packages have their options fixed at install time.

External

To use this library from a CMake project, you can locate it directly with find_package() and use the namespaced imported target from the generated package configuration:

!!! example

```cmake title="CMakeLists.txt"
cmake_minimum_required(VERSION 3.5)
project(ExampleProject LANGUAGES CXX)

find_package(nlohmann_json 3.12.0 REQUIRED)

add_executable(example example.cpp)
target_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)
```

The package configuration file, nlohmann_jsonConfig.cmake, can be used either from an install tree or directly out of the build tree.

Embedded

To embed the library directly into an existing CMake project, place the entire source tree in a subdirectory and call add_subdirectory() in your CMakeLists.txt file.

!!! example

```cmake title="CMakeLists.txt"
cmake_minimum_required(VERSION 3.5)
project(ExampleProject LANGUAGES CXX)

# If you only include this third party in PRIVATE source files, you do not need to install it
# when your main project gets installed.
set(JSON_Install OFF CACHE INTERNAL "")

add_subdirectory(nlohmann_json)

add_executable(example example.cpp)
target_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)
```

!!! note

Do not use `#!cmake include(nlohmann_json/CMakeLists.txt)`, since that carries with it unintended consequences that
will break the build. It is generally discouraged (although not necessarily well documented as such) to use
`#!cmake include(...)` for pulling in other CMake projects anyways.

Supporting Both

To allow your project to support either an externally supplied or an embedded JSON library, you can use a pattern akin to the following.

!!! example

```cmake title="CMakeLists.txt"
project(ExampleProject LANGUAGES CXX)

option(EXAMPLE_USE_EXTERNAL_JSON "Use an external JSON library" OFF)

add_subdirectory(thirdparty)

add_executable(example example.cpp)

# Note that the namespaced target will always be available regardless of the import method
target_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)
```

```cmake title="thirdparty/CMakeLists.txt"
if(EXAMPLE_USE_EXTERNAL_JSON)
    find_package(nlohmann_json 3.12.0 REQUIRED)
else()
    set(JSON_BuildTests OFF CACHE INTERNAL "")
    add_subdirectory(nlohmann_json)
endif()
```

`thirdparty/nlohmann_json` is then a complete copy of this source tree.

FetchContent

Since CMake v3.14, FetchContent can be used to automatically download a release as a dependency at configure time.

!!! example

```cmake title="CMakeLists.txt"
cmake_minimum_required(VERSION 3.14)
project(ExampleProject LANGUAGES CXX)

include(FetchContent)

FetchContent_Declare(json URL https://github.com/nlohmann/json/releases/download/v3.12.0/json.tar.xz)
FetchContent_MakeAvailable(json)

add_executable(example example.cpp)
target_link_libraries(example PRIVATE nlohmann_json::nlohmann_json)
```

!!! Note

It is recommended to use the URL approach described above which is supported as of version 3.10.0. It is also
possible to pass the Git repository like

```cmake
FetchContent_Declare(json
    GIT_REPOSITORY https://github.com/nlohmann/json
    GIT_TAG v3.12.0
)
```

However, the repository <https://github.com/nlohmann/json> download size is quite large.

CMake Options

JSON_BuildTests

Build the unit tests when BUILD_TESTING is enabled. This option is ON by default if the library's CMake project is the top project and the tests directory exists (the release archive json.tar.xz does not contain it). That is, when integrating the library as described above, the test suite is not built unless explicitly switched on with this option.

JSON_CI

Enable CI build targets. The exact targets are used during the several CI steps and are subject to change without notice. This option is OFF by default.

JSON_DeleteDeprecatedFunctions

Delete the deprecated functions instead of only deprecating them by defining the macro JSON_DELETE_DEPRECATED_FUNCTIONS. This option is OFF by default.

JSON_Diagnostics

Enable extended diagnostic messages by defining macro JSON_DIAGNOSTICS. This option is OFF by default.

!!! warning "Does not apply to a pre-installed package"

This option only takes effect when building nlohmann/json from source as part of your own
CMake project (e.g. via [`FetchContent`](#fetchcontent) or [`add_subdirectory`](#embedded)).
It has **no effect** on a package that was already built and installed elsewhere (Homebrew,
vcpkg, a system package, etc.) — the resulting compile definition is baked into the exported
`nlohmann_jsonTargets.cmake` at install time, and `set(JSON_Diagnostics ON)` before
`find_package()` does not change it (verified against the Homebrew-installed package: the
exported target still carries a fixed `$<$<BOOL:OFF>:JSON_DIAGNOSTICS=1>`, regardless of any
variable set in the consuming project).

To enable extended diagnostics for a pre-installed package, override the imported target's
property directly after `find_package()`:

```cmake
find_package(nlohmann_json REQUIRED)
set_target_properties(nlohmann_json::nlohmann_json PROPERTIES
    INTERFACE_COMPILE_DEFINITIONS "JSON_DIAGNOSTICS=1")
```

This only works cleanly when your project is the sole consumer of that imported target. If
nlohmann_json is pulled in from more than one place in your dependency graph with different
`JSON_DIAGNOSTICS` values, you may see a `"JSON_DIAGNOSTICS" redefined` compiler error, since
conflicting `-D` flags can end up on the same compile command line.

JSON_Diagnostic_Positions

Enable position diagnostics by defining macro JSON_DIAGNOSTIC_POSITIONS. This option is OFF by default.

JSON_DisableEnumSerialization

Disable default enum serialization by defining the macro JSON_DISABLE_ENUM_SERIALIZATION. This option is OFF by default.

JSON_DisableTupleReferenceConversion

Disable the conversion from a one-element std::tuple holding a reference to a JSON value by defining the macro JSON_DISABLE_TUPLE_REFERENCE_CONVERSION. This option is OFF by default.

JSON_FastTests

Skip expensive/slow test suites. This option is OFF by default. Depends on JSON_BuildTests.

JSON_GlobalUDLs

Place user-defined string literals in the global namespace by defining the macro JSON_USE_GLOBAL_UDLS. This option is ON by default; see the migration guide for how to prepare code for the next major release, where the literals are removed from the global namespace.

JSON_ImplicitConversions

Enable implicit conversions by defining macro JSON_USE_IMPLICIT_CONVERSIONS. This option is ON by default; see the migration guide for how to prepare code for the next major release, where implicit conversions are switched off by default.

JSON_Install

Install CMake targets during install step. This option is ON by default if the library's CMake project is the top project. Installing also generates a pkg-config file for tools that rely on pkg-config instead of CMake.

JSON_LegacyDiscardedValueComparison

Enable the (incorrect) legacy comparison behavior of discarded JSON values by defining macro JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON. This option is OFF by default.

JSON_MultipleHeaders

Use the non-amalgamated version of the library. This option is ON by default.

JSON_SystemInclude

Treat the library headers like system headers (i.e., adding SYSTEM to the target_include_directories call) to check for this library by tools like Clang-Tidy. This option is OFF by default.

JSON_StrictBinaryUTF8

Check string values and object keys for valid UTF-8 in the CBOR, UBJSON, BJData, and BSON writers, by defining the macro JSON_STRICT_BINARY_UTF8. This option is OFF by default.

JSON_StrictNulHandling

Reject a '\0' (NUL) byte in the input instead of treating it as end of input, by defining the macro JSON_STRICT_NUL_HANDLING. This option is OFF by default.

JSON_TestSimdutf

Build the unit tests against the simdutf UTF-8 validation backend by defining JSON_USE_SIMDUTF for every test target. simdutf is fetched during configuration; its version is set by the cache variable JSON_SIMDUTF_VERSION. This option is OFF by default. Depends on JSON_BuildTests.

JSON_Valgrind

Execute the test suite with Valgrind. This option is OFF by default. Depends on JSON_BuildTests.

NLOHMANN_JSON_BUILD_MODULES

Build the experimental C++ module nlohmann.json (requires CMake 3.28 or later and C++20). This option is OFF by default.

A consuming project must link the dedicated nlohmann_json_modules CMake target (not just nlohmann_json::nlohmann_json) for import nlohmann.json; to resolve:

set(NLOHMANN_JSON_BUILD_MODULES ON)
add_subdirectory(path/to/json)

add_executable(myproject main.cpp)
target_link_libraries(myproject PRIVATE nlohmann_json_modules)
target_compile_definitions(myproject PRIVATE NLOHMANN_JSON_BUILD_MODULES)

See also