Use a const char* rather than a char[] lookup table, matching the
existing hex_bytes helper in the same file.
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
dump_escaped called std::snprintf(..., "\u%04x", ...) once per escaped
code point in the string serialization hot path. snprintf re-parses
the format string and pulls in locale/printf machinery on every call,
which is far heavier than the fixed 6-/12-byte output warrants. This
is hot for any string containing control characters, and for all
non-ASCII text when ensure_ascii is set.
Replace it with write_u_escape, a small helper that writes the escape
directly into string_buffer via a nibble-to-hex lookup table, mirroring
the existing hand-rolled dump_integer fast path in the same file.
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* Harden CI workflows: validate PR artifact inputs and migrate off deprecated Semgrep action
Address two CI/supply-chain hardening items from the 2026-07-03 security
audit:
- comment_check_amalgamation.yml (todo 117): the privileged `workflow_run`
job consumes an untrusted PR artifact. Validate `author` against a strict
GitHub-username pattern and `number` as a positive integer before use, and
extract the artifact into a dedicated directory (`unzip -o pr.zip -d
./pr_artifact`), reading only the two expected files by fixed path. This
prevents Markdown/mention injection via the attacker-controlled `author`
text and avoids a malicious archive touching the workspace.
- semgrep.yml (todo 118): `returntocorp/semgrep-action` is deprecated (the
org was renamed to `semgrep/*`). Replace it with an explicit `semgrep ci`
invocation via the maintained CLI; the deployment is inferred from
SEMGREP_APP_TOKEN.
Todo 116 (CIFuzz `@master` refs) already carries a comment documenting the
OSS-Fuzz-recommended exception, so no change is needed there.
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* Fix Semgrep step: use `semgrep scan` instead of token-gated `semgrep ci`
The CI `Scan` job failed with "Path does not exist: semgrep.sarif" because
`semgrep ci` requires a login token (SEMGREP_APP_TOKEN), which this repo does
not have configured, so it bailed without producing a SARIF file. The former
returntocorp/semgrep-action, given no token, fell back to plain
`semgrep scan --sarif`; match that with `semgrep scan --config auto`, which
needs no token and always produces the SARIF for upload.
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Bumps init/analyze/autobuild together (previously split across #5226,
#5227, #5228, which each failed CI due to a version mismatch between
the CodeQL config and the running action). Also adds a dependabot
group so future codeql-action bumps land in a single PR.
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
When a PR is not amalgamated/formatted, the astyle version friction (see
the recurring blocker across many PRs) means contributors often struggle
to reproduce the exact fix locally. The check now regenerates the
amalgamation and formatting, captures the difference as a patch, and
uploads it as the `amalgamation-patch` artifact. The failure comment
links to that artifact and tells contributors to run
`git apply amalgamation.patch`, so they no longer need to install the
pinned astyle version themselves.
The pass/fail verdict is unchanged: the same PRs fail as before, and a
correctly amalgamated PR uploads nothing and passes.
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Add /wd4702 to disable warning C4702: unreachable code in MSVC Release build.
Signed-off-by: Richard Musil <risa2000x@gmail.com>
Co-authored-by: Richard Musil <risa2000x@gmail.com>
* Added NLOHNMANN_JSON_SERIALIZE_ENUM_STRICT
- duplicate of NLOHMANN_JSON_SERIALIZE_ENUM
Signed-off-by: Caillin Nugent <caillinn@student.unimelb.edu.au>
* Added failing tests for NLOHMANN_JSON_SERIALIZE_ENUM_STRICT
Signed-off-by: Caillin Nugent <caillinn@student.unimelb.edu.au>
* modified NLOHMANN_JSON_SERIALIZE_STRICT to throw
Signed-off-by: Caillin Nugent <caillinn@student.unimelb.edu.au>
* added documentation and changed readme to include NLOHMANN_JSON_SERIALIZE_ENUM_STRICT
Signed-off-by: Caillin Nugent <caillinn@student.unimelb.edu.au>
* ran amalgamate
Signed-off-by: Caillin Nugent <caillinn@student.unimelb.edu.au>
* docs(macros): add page for JSON_SERIALIZE_ENUM_STRICT
- added page to nav
- added links to new page where appropriate
Signed-off-by: Caillin Nugent <caillinn@student.unimelb.edu.au>
* refactor(macros): make JSON_SERIALIZE_ENUM_STRICT use JSON_THROW
- added templated wrapper function to fix scope error in calling JSON_THROW
Signed-off-by: Caillin Nugent <caillinn@student.unimelb.edu.au>
* refactor(macros): make NLOHMANN_SERIALIZE_ENUM_STRICT use error code 410
- added error code 410 to docs
Signed-off-by: Caillin Nugent <caillinn@student.unimelb.edu.au>
* tests(macros): add test for to_json with enum value not mentioned
in mapping for NLOHMANN_JSON_SERIALIZE_ENUM_STRICT
Signed-off-by: Caillin Nugent <caillinn@student.unimelb.edu.au>
* Apply suggestions from code review
Co-authored-by: Niels Lohmann <niels.lohmann@gmail.com>
Signed-off-by: Caillin Nugent <nugentcaillin@gmail.com>
* fix(macro): prevent compilation error with -Werror and -Wunused-parameter
with NLOHMANN_JSON_SERIALIZE_ENUM_STRICT
- casted exception to void to avoid warning
Signed-off-by: Caillin Nugent <caillinn@student.unimelb.edu.au>
* fix(docs): add link to NLOHMANN_SERIALIZE_ENUM_STRICT docs to exception page
Signed-off-by: Caillin Nugent <caillinn@student.unimelb.edu.au>
* docs(macros): add example of exception throwing for NLOHMANN_JSON_SERIALIZE_ENUM_STRICT
Signed-off-by: Caillin Nugent <caillinn@student.unimelb.edu.au>
* refactor(macros): add more in-depth error message to NLOHMANN_JSON_SERIALIZE_ENUM_STRICT
- changed error message to follow style of nlohmann/json#4989
- made description of throw wrapper more general
- updated tests and example of exceptions
Signed-off-by: Caillin Nugent <caillinn@student.unimelb.edu.au>
---------
Signed-off-by: Caillin Nugent <caillinn@student.unimelb.edu.au>
Signed-off-by: Caillin Nugent <nugentcaillin@gmail.com>
Co-authored-by: Niels Lohmann <niels.lohmann@gmail.com>
* Fix for printing long doubles bug in dump_float
When you use long double as a floating point type with the current version of this file and try to dump json it prints trash instead of actual number. This if-else fixes the problem. On using long double you just need to add an 'L' modifier before 'g' in format string.
Signed-off-by: Kirill Lokotkov <klokotkov@ya.ru>
* C++11 compatibility
Signed-off-by: Kirill Lokotkov <klokotkov@ya.ru>
* Shorter solution
Signed-off-by: Kirill Lokotkov <klokotkov@ya.ru>
* Applied amalgamate
Signed-off-by: rusloker <klokotkov@ya.ru>
* Add unit tests for `dump()` with `long double` in custom `basic_json`
Signed-off-by: rusloker <klokotkov@ya.ru>
* Fix UB in `snprintf_float` by using `%.*Lg` for `long double`
Signed-off-by: rusloker <klokotkov@ya.ru>
* Use `std::array` for `values` in serialization unit tests to improve type safety
Signed-off-by: rusloker <klokotkov@ya.ru>
* Fix brace initialization for `std::array` in serialization unit tests
Signed-off-by: rusloker <klokotkov@ya.ru>
* Remove comments in `snprintf_float` regarding `%Lg` usage
Signed-off-by: rusloker <klokotkov@ya.ru>
* Skip `long double` infinity dump assertions under Valgrind
Signed-off-by: rusloker <klokotkov@ya.ru>
* Clarify Valgrind bug-tracker reference in `long double` test
Signed-off-by: rusloker <klokotkov@ya.ru>
* Satisfy clang-tidy in `long double` infinity probe
Signed-off-by: rusloker <klokotkov@ya.ru>
---------
Signed-off-by: Kirill Lokotkov <klokotkov@ya.ru>
Signed-off-by: rusloker <klokotkov@ya.ru>
* Add new macros for named conversions
* Unit tests for the named conversion macros
* Update the docs to include the new macros
* Fix the documentation for the macros
the correct maximum number of member variables is 63
* Fix CI tests
* update the named macros
* move the example files
* update the explicit macros expansion
* update documentation
* fix documentation hiccups
* astyle changes
* add static analysis exceptions
* change md header to explicit html to fit the length
* Small corrections to docs
Co-authored-by: Niels Lohmann <niels.lohmann@gmail.com>
Signed-off-by: George Sedov <radist.morse@gmail.com>
---------
Signed-off-by: George Sedov <radist.morse@gmail.com>
Co-authored-by: Niels Lohmann <niels.lohmann@gmail.com>
* Fix compile error when using nlohmann ordered_map with WITH_DEFAULT macros
ordered_map inherits its copy and move assignment from the underlying std vector, which requires value_type to be CopyAssignable. value_type is pair<const Key, T> whose assignment is deleted because of the const Key, so any code that assigns ordered_map (for example the ternary in NLOHMANN_JSON_FROM_WITH_DEFAULT) fails to compile (issue #5122). Provide assignment operators on ordered_map that rebuild via clear plus push_back for copy and transfer the underlying buffer for move, neither of which needs pair assignment. Also switch the map-shaped from_json overload from a transform plus inserter idiom to a range-for plus emplace, which avoids the same hazard.
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* Update ordered_map.hpp
removed unwanted comments
Signed-off-by: SamareshSingh <97642706+ssam18@users.noreply.github.com>
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* Update json.hpp
Signed-off-by: SamareshSingh <97642706+ssam18@users.noreply.github.com>
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* Address CI issues for ordered_map fix
Declare an explicit defaulted destructor on ordered_map so the rule of five is complete (clang-tidy cppcoreguidelines-special-member-functions and hicpp-special-member-functions). Initialize the ordered_map field in the regression test struct so GCC effective-C++ stops flagging Example_5122 with a missing member initializer.
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* Suppress redundant-member-init lint on Example_5122::c
The empty brace-init on c{} is required by GCC -Weffc++ to mark the member as initialized in the synthesized default constructor, but clang-tidy readability-redundant-member-init flags the same line because ordered_map already has a default constructor. The two checks pull in opposite directions, so add a targeted NOLINT to keep both happy.
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* Address review: strong exception safety in copy-assign, simplify move-assign noexcept
Copy assignment now constructs a temporary copy before move-assigning the
Container subobject, preserving *this if the copy throws. Move assignment
uses std::is_nothrow_move_assignable<Container> for a cleaner noexcept
specifier, matching the style of the move constructor.
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* Restore self-assignment check in copy-assign to satisfy cert-oop54-cpp
clang-tidy's cert-oop54-cpp flagged the previous revision because it could
not recognize the implicit self-safety of the copy-then-move pattern.
Restore the explicit `if (this != &other)` guard — strong exception safety
is preserved since the temporary copy is still constructed before the
move-assign of the Container subobject.
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* Address review: add explicit self-assignment and move-assignment tests for ordered_map
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* Address review: gate -Wself-assign-overloaded suppression on Clang version
-Wself-assign-overloaded was introduced in Clang 7. Older Clang versions fail the build with "unknown warning group" when the suppression pragma references it unconditionally. Use __has_warning inside an __clang__ branch so the suppression is only emitted on Clang versions that recognize the warning. The inner check stays inside the __clang__ guard because GCC does not provide __has_warning and would tokenize-error on the argument list.
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* Address CI: drop unused gating macro to silence -Wunused-macros
The previous attempt defined JSON_TEST_5122_SUPPRESS_SELF_ASSIGN_OVERLOADED
as 0 unconditionally and then overrode it to 1 on Clang versions that recognize the warning. On those Clangs the initial define is immediately
undef'd without being read, which trips Clang's -Wunused-macros under -Weverything in the ci_test_clang job. Drop the macro and gate the
DOCTEST_CLANG_SUPPRESS_WARNING_PUSH/POP pragmas directly with __has_warning inside the existing __clang__ branch.
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
---------
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
Signed-off-by: SamareshSingh <97642706+ssam18@users.noreply.github.com>
When iteration_proxy_value<iter_impl<ordered_json>> appears in a context
that requires it to be complete (function or lambda parameter), the
compiler instantiates basic_json<ordered_map> and walks into
set_parents(iterator, typename iterator::difference_type)
while iterator is still incomplete, failing with "invalid use of
incomplete type".
basic_json::difference_type is already std::ptrdiff_t, so just naming
the underlying type directly avoids the dependent lookup. Behavior and
ABI are unchanged. This was the approach suggested in the issue thread.
Added a regression case in unit-ordered_json.cpp using the same trigger
pattern (lambda parameter naming the proxy type).
Fixes#3732
Signed-off-by: Akhilesh Arora <akhildawra@gmail.com>
* fix: treat single-element brace-init as copy/move
When passing a json value using brace initialization with a single element
(e.g., `json j{someObj}` or `foo({someJson})`), C++ always prefers the
initializer_list constructor over the copy/move constructor. This caused
the value to be unexpectedly wrapped in a single-element array.
This bug was previously compiler-dependent (GCC wrapped, Clang did not),
but Clang 20 started matching GCC behavior, making it a universal issue.
Fix: In the initializer_list constructor, when type deduction is enabled
and the list has exactly one element, copy/move it directly instead of
creating a single-element array.
Before:
json obj = {{"key", 1}};
json j{obj}; // -> [{"key":1}] (wrong: array)
foo({obj}); // -> [{"key":1}] (wrong: array)
After:
json j{obj}; // -> {"key":1} (correct: copy)
foo({obj}); // -> {"key":1} (correct: copy)
To explicitly create a single-element array, use json::array({value}).
Fixes the issue #5074
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* fix: regenerate amalgamated single_include/nlohmann/json.hpp
- Add missing comment from include/nlohmann/json.hpp explaining the
single-element brace-init fix (issue #5074)
- Fix extra 4-space indentation in embedded json_fwd.hpp section
Regenerated by running: make amalgamate
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* Revert brace-init semantics change and fix amalgamation
The single-element brace-init change was a breaking change that cannot be accepted upstream. Reverted all related source, test, and doc changes, then regenerated single_include with correct indentation to pass the amalgamation CI check.
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* Fix: add JSON_BRACE_INIT_COPY_SEMANTICS opt-in macro for issue #5074
Single-element brace initialization wrapping in an array cannot be fixed without breaking existing code. Added JSON_BRACE_INIT_COPY_SEMANTICS as an opt-in macro (default 0) so users can enable copy/move semantics for single-element brace init without affecting anyone relying on the current behavior.
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* docs: add dedicated macro page and CI test target for JSON_BRACE_INIT_COPY_SEMANTICS
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* fix: remove compiler-dependent assertions from #5074 regression test
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* fix: use defined() guard for JSON_BRACE_INIT_COPY_SEMANTICS to satisfy -Wundef
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* docs: fix section name in json_brace_init_copy_semantics.md to pass style check
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* docs: move Default definition section before Notes to fix style check order
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
---------
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
PR #4873 introduced a safety check in sax_parse functions to catch
nullptr passed as SAX parser object, which had been already annotated by
JSON_HEDLEY_NON_NULL macro.
Compilers (e.g. clang) which respected the non-null annotation tended to
eliminate the safety check completely in optimized builds, while
compilers which did not, compiled the safety check in. This led to
different behaviors accross different compilers/platforms and/or build
types (debug, release).
This commit reverts PR #4873 to remove this discrepancy. Passing null to
non-null annotated parameter is considered to be undefined behavior.
Fixes#5048
Signed-off-by: Richard Musil <risa2000x@gmail.com>
Co-authored-by: Richard Musil <risa2000x@gmail.com>
* Add reference handling to tuples
Signed-off-by: Evelyn LePain <ava.lepain@gmail.com>
* Remove template template type because pair isn't working
Signed-off-by: Evelyn LePain <ava.lepain@gmail.com>
* amalgamate std::tie changes
Signed-off-by: Evelyn LePain <ava.lepain@gmail.com>
* allow the elation of a move by removing the ref requirement
Signed-off-by: Evelyn LePain <ava.lepain@gmail.com>
* force all number_xxx_t to be interchangeable
Signed-off-by: Evelyn LePain <ava.lepain@gmail.com>
* Finally got amalgamate to work correctly
Signed-off-by: Evelyn LePain <ava.lepain@gmail.com>
* remove const version, add a test case for scrambled number representations.
Signed-off-by: Evelyn LePain <ava.lepain@gmail.com>
* Use the logical set of requirements instead of decltype because VS 2015 doesn't like it
Signed-off-by: Evelyn LePain <ava.lepain@gmail.com>
---------
Signed-off-by: Evelyn LePain <ava.lepain@gmail.com>
* fix(cbor): reject negative ints overflowing int64
CBOR encodes negative integers as "-1 - n" where n is uint64_t. When
n > INT64_MAX, casting to int64_t caused undefined behavior and silent
data corruption. Large negative values were incorrectly parsed as
positive integers (e.g., -9223372036854775809 became 9223372036854775807).
Add bounds check for to reject values that exceed int64_t
representable range, returning parse_error instead of silently
corrupting data.
Added regression test cases to verify.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* chore: clarify tests
Add test for "n=0" case (result=-1) to cover the smallest magnitude
boundary. Update comments to explain CBOR 0x3B encoding and why
"result=0" is not possible. Clarify that n is an unsigned integer
in the formula "result = -1 - n" to help understanding the tests.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
* fix(cbor): extend overflow checks for other types
Extend negative integer overflow detection to all CBOR negative
integer cases (0x38, 0x39, 0x3A) for consistency with the existing
0x3B check.
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
---------
Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
Fixes#3659
I was testing serve_header.py with my local development setup and noticed
that when I moved directories into or out of the monitored root, they
weren't being picked up properly. The script would only detect create and
delete events but not move operations.
This was happening because the on_any_event handler only checked for
'created' and 'deleted' events on directories. Move events have a
separate event type 'moved' that includes both the source and destination
paths.
The fix treats a move event like a combination of delete (for the source)
and create (for the destination) - we rescan to remove any trees that were
moved out, and add the destination directory to check for new trees that
were moved in.
This should make the development workflow smoother when reorganizing
project directories while the server is running.
Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
* Improve MSVC C++ modules compatibility for nlohmann_json
- Keep complete module interface with all exports
- Export all standard types: json, basic_json, adl_serializer, json_pointer, ordered_json, ordered_map
- Export detail namespace symbols for advanced usage
- Ensure compatibility with MSVC C++20/23 modules
- Maintain full functionality without breaking changes
Signed-off-by: yudaichen <250074249@qq.com>
* Add C++20 module Windows CI test and fix file ending
- Add ci_module_cpp20 job to Windows workflow to verify module support with MSVC
- Add missing newline at end of json.cppm file
Signed-off-by: yudaichen <250074249@qq.com>
---------
Signed-off-by: yudaichen <250074249@qq.com>
* 👷 fix Windows CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* 👷 fix Windows CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* 👷 fix Windows CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* 👷 fix Windows CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* 👷 fix Windows CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* 👷 fix Windows CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* 👷 fix Windows CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* 👷 fix Windows CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* 👷 fix Windows CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* 👷 fix Windows CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* 👷 fix Windows CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* 👷 fix Windows CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* 👷 fix Windows CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
* 👷 fix Windows CI
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
---------
Signed-off-by: Niels Lohmann <mail@nlohmann.me>
@@ -153,6 +153,9 @@ files directly; instead, modify the include/nlohmann sources and regenerate the
make amalgamate
```
Running `make amalgamate` will also apply automatic formatting to the source files using
[`Artistic Style`](https://astyle.sourceforge.net/). This formatting may modify your source files in-place. Be certain to review and commit any changes to avoid unintended formatting diffs in commits.
## Recommended documentation
- The library’s [README file](https://github.com/nlohmann/json/blob/master/README.md) is an excellent starting point to
We would appreciate it if you could provide us with more info about this issue or pull request! Please check the [issue template](https://github.com/nlohmann/json/blob/develop/.github/ISSUE_TEMPLATE.md) and the [pull request template](https://github.com/nlohmann/json/blob/develop/.github/PULL_REQUEST_TEMPLATE.md).
We would appreciate it if you could provide us with more info about this issue or pull request! Please check the [issue template](https://github.com/nlohmann/json/issues/new/choose) and the [pull request template](https://github.com/nlohmann/json/blob/develop/.github/PULL_REQUEST_TEMPLATE.md).
# *OPTIONAL* Label to be added to Issues and Pull Requests with insufficient information given
@@ -9,6 +9,30 @@ This file describes the source for supporting files; that is, files that are not
## Continuous Integration
### `.github/workflows`
The [GitHub Actions](https://docs.github.com/en/actions) workflows that build, test, and analyze the library. Each file in this folder defines one workflow:
-`ubuntu.yml`, `macos.yml`, `windows.yml` — build and run the test suite on Linux, macOS, and Windows.
-`check_amalgamation.yml` — verify that the single-header amalgamation in `single_include` is up to date on pull requests.
-`comment_check_amalgamation.yml` — comment on a pull request when the amalgamation check failed.
-`cifuzz.yml` — run short fuzzing sessions via [OSS-Fuzz CIFuzz](https://google.github.io/oss-fuzz/getting-started/continuous-integration/) on pull requests.
-`codeql-analysis.yml` — run [CodeQL](https://codeql.github.com) code scanning.
-`flawfinder.yml` — run the [Flawfinder](https://dwheeler.com/flawfinder/) static analysis.
-`semgrep.yml` — run [Semgrep](https://semgrep.dev) static analysis.
-`scorecards.yml` — run the [OpenSSF Scorecard](https://securityscorecards.dev) supply-chain security checks.
-`dependency-review.yml` — scan dependency changes in pull requests for known vulnerabilities.
-`labeler.yml` — the "Pull Request Labeler" workflow (see `.github/labeler.yml`).
-`stale.yml` — comment on and close stale issues and pull requests.
-`publish_documentation.yml` — build and publish the documentation on every merge to the `develop` branch.
Further documentation:
- [Workflow syntax for GitHub Actions](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions)
> [!IMPORTANT]
> The folder `.github/workflows` is predetermined by GitHub.
### `.cirrus.yml`
Configuration file for the pipeline at [Cirrus CI](https://cirrus-ci.com/github/nlohmann/json).
@@ -123,7 +147,7 @@ Further documentation:
> [!IMPORTANT]
> The folder `.github/ISSUE_TEMPLATE` is predetermined by GitHub.
### `.github/ISSUE_TEMPLATE/config.yaml`
### `.github/ISSUE_TEMPLATE/config.yml`
Issue template chooser configuration. The file is used to configure the dialog when a new issue is created.
@@ -132,7 +156,7 @@ Further documentation:
- [Configuring issue templates for your repository](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/configuring-issue-templates-for-your-repository)
> [!IMPORTANT]
> The filename `.github/ISSUE_TEMPLATE/config.yaml` is predetermined by GitHub.
> The filename `.github/ISSUE_TEMPLATE/config.yml` is predetermined by GitHub.
### `.github/labeler.yml`
@@ -165,7 +189,7 @@ Further documentation:
- [Adding a security policy to your repository](https://docs.github.com/en/code-security/getting-started/adding-a-security-policy-to-your-repository)
> [!IMPORTANT]
> The filename `.github/SECURITY.yml` is predetermined by GitHub.
> The filename `.github/SECURITY.md` is predetermined by GitHub.
> [!NOTE]
> The file is part of the documentation and is included in `docs/mkdocs/docs/community/security_policy.md`.
@@ -234,6 +258,16 @@ make BUILD.bazel
### `meson.build`
The build definition for the [Meson](https://mesonbuild.com) build system.
### `Package.swift`
### `WORKSPACE.bazel`
The package manifest for the [Swift Package Manager](https://www.swift.org/package-manager/).
### `MODULE.bazel`
The module definition for [Bazel](https://bazel.build)'s [Bzlmod](https://bazel.build/external/module) dependency system. It complements `BUILD.bazel` and replaces the previously used `WORKSPACE.bazel`.
[](https://isitmaintained.com/project/nlohmann/json "Average time to resolve an issue")
[](https://bestpractices.coreinfrastructure.org/projects/289)
@@ -69,7 +70,7 @@ Other aspects were not so important to us:
- **Speed**. There are certainly [faster JSON libraries](https://github.com/miloyip/nativejson-benchmark#parsing-time) out there. However, if your goal is to speed up your development by adding JSON support with a single header, then this library is the way to go. If you know how to use a `std::vector` or `std::map`, you are already set.
See the [contribution guidelines](https://github.com/nlohmann/json/blob/master/.github/CONTRIBUTING.md#please-dont) for more information.
See the [contribution guidelines](https://github.com/nlohmann/json/blob/develop/.github/CONTRIBUTING.md#please-dont) for more information.
## Sponsors
@@ -79,6 +80,8 @@ You can sponsor this library at [GitHub Sponsors](https://github.com/sponsors/nl
That's all! When calling the `json` constructor with your type, your custom `to_json` method will be automatically called.
Likewise, when calling `template get<your_type>()` or `get_to(your_type&)`, the `from_json` method will be called.
Likewise, when calling `get<your_type>()` or `get_to(your_type&)`, the `from_json` method will be called.
Some important things:
- Those methods **MUST** be in your type's namespace (which can be the global namespace), or the library will not be able to locate them (in this example, they are in namespace `ns`, where `person` is defined).
- Those methods **MUST** be available (e.g., proper headers must be included) everywhere you use these conversions. Look at [issue 1108](https://github.com/nlohmann/json/issues/1108) for errors that may occur otherwise.
- When using `template get<your_type>()`, `your_type`**MUST** be [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). (There is a way to bypass this requirement described later.)
- When using `get<your_type>()`, `your_type`**MUST** be [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). (There is a way to bypass this requirement described later.)
- In function `from_json`, use function [`at()`](https://json.nlohmann.me/api/basic_json/at/) to access the object values rather than `operator[]`. In case a key does not exist, `at` throws an exception that you can handle, whereas `operator[]` exhibits undefined behavior.
- You do not need to add serializers or deserializers for STL types like `std::vector`: the library already implements these.
#### Simplify your life with macros
If you just want to serialize/deserialize some structs, the `to_json`/`from_json` functions can be a lot of boilerplate. There are [**several macros**](https://json.nlohmann.me/features/arbitrary_types/#simplify-your-life-with-macros) to make your life easier as long as you (1) want to use a JSON object as serialization and (2) want to use the member variable names as object keys in that object.
If you just want to serialize/deserialize some structs, the `to_json`/`from_json` functions can be a lot of boilerplate. There are [**several macros**](https://json.nlohmann.me/api/macros/#serializationdeserialization-macros) to make your life easier as long as you want to use a JSON object as serialization.
Which macro to choose depends on whether private member variables need to be accessed, a deserialization is needed, missing values should yield an error or should be replaced by default values, and if derived classes are used. See [this overview to choose the right one for your use case](https://json.nlohmann.me/api/macros/#serializationdeserialization-macros).
Which macro to choose depends on whether private member variables need to be accessed, a deserialization is needed, missing values should yield an error or should be replaced by default values, and if derived classes are used. See [this overview to choose the right one for your use case](https://json.nlohmann.me/features/arbitrary_types/#simplify-your-life-with-macros).
##### Example usage of macros
@@ -853,6 +871,18 @@ namespace ns {
}
```
If you want to inherit the `person` struct and add a field to it, it can be done with:
Here is another example with private members, where [`NLOHMANN_DEFINE_TYPE_INTRUSIVE`](https://json.nlohmann.me/api/macros/nlohmann_define_type_intrusive/) is needed:
```cpp
@@ -869,6 +899,24 @@ namespace ns {
}
```
Or in case if you use some naming convention that you do not want to expose to JSON:
This requires a bit more advanced technique. But first, let's see how this conversion mechanism works:
@@ -913,8 +961,8 @@ namespace nlohmann {
if(j.is_null()){
opt=boost::none;
}else{
opt=j.templateget<T>();// same as above, but with
// adl_serializer<T>::from_json
opt=j.get<T>();// same as above, but with
// adl_serializer<T>::from_json
}
}
};
@@ -941,7 +989,7 @@ namespace nlohmann {
// note: the return type is no longer 'void', and the method only takes
// one argument
staticmove_only_typefrom_json(constjson&j){
return{j.templateget<int>()};
return{j.get<int>()};
}
// Here's the catch! You must provide a to_json method! Otherwise, you
@@ -1005,7 +1053,7 @@ struct bad_serializer
staticvoidto_json(constBasicJsonType&j,T&value){
// this calls BasicJsonType::json_serializer<T>::from_json(j, value)
// if BasicJsonType::json_serializer == bad_serializer ... oops!
value=j.templateget<T>();// oops!
value=j.get<T>();// oops!
}
};
```
@@ -1045,11 +1093,11 @@ assert(j == "stopped");
// json string to enum
jsonj3="running";
assert(j3.templateget<TaskState>()==TS_RUNNING);
assert(j3.get<TaskState>()==TS_RUNNING);
// undefined json value to enum (where the first map entry above is the default)
jsonjPi=3.14;
assert(jPi.templateget<TaskState>()==TS_INVALID);
assert(jPi.get<TaskState>()==TS_INVALID);
```
Just as in [Arbitrary Type Conversions](#arbitrary-types-conversions) above,
@@ -1059,7 +1107,7 @@ Just as in [Arbitrary Type Conversions](#arbitrary-types-conversions) above,
Other Important points:
- When using `template get<ENUM_TYPE>()`, undefined JSON values will default to the first pair specified in your map. Select this default pair carefully.
- When using `get<ENUM_TYPE>()`, undefined JSON values will default to the first pair specified in your map. Select this default pair carefully. If you desire an exception in this circumstance use `NLOHMANN_JSON_SERIALIZE_ENUM_STRICT()` which behaves identically except for throwing an exception on unrecognized values.
- If an enum or JSON value is specified more than once in your map, the first matching occurrence from the top of the map will be returned when converting to or from JSON.
### Binary formats (BSON, CBOR, MessagePack, UBJSON, and BJData)
@@ -1141,7 +1189,7 @@ The library is used in multiple projects, applications, operating systems, etc.
## Supported compilers
Though it's 2025 already, the support for C++11 is still a bit sparse. Currently, the following compilers are known to work:
Though it's 2026 already, the support for C++11 is still a bit sparse. Currently, the following compilers are known to work:
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
@@ -1419,7 +1467,7 @@ I deeply appreciate the help of the following people.
57. [Jared Grubb](https://github.com/jaredgrubb) supported the implementation of user-defined types.
58. [EnricoBilla](https://github.com/EnricoBilla) noted a typo in an example.
59. [Martin Hořeňovský](https://github.com/horenmar) found a way for a 2x speedup for the compilation time of the test suite.
60. [ukhegg](https://github.com/ukhegg) found proposed an improvement for the examples section.
60. [ukhegg](https://github.com/ukhegg) proposed an improvement for the examples section.
61. [rswanson-ihi](https://github.com/rswanson-ihi) noted a typo in the README.
62. [Mihai Stan](https://github.com/stanmihai4) fixed a bug in the comparison with `nullptr`s.
63. [Tushar Maheshwari](https://github.com/tusharpm) added [cotire](https://github.com/sakra/cotire) support to speed up the compilation.
@@ -1793,7 +1841,7 @@ The library supports **Unicode input** as follows:
This library does not support comments by default. It does so for three reasons:
1. Comments are not part of the [JSON specification](https://tools.ietf.org/html/rfc8259). You may argue that `//` or `/* */` are allowed in JavaScript, but JSON is not JavaScript.
2. This was not an oversight: Douglas Crockford [wrote on this](https://plus.google.com/118095276221607585885/posts/RK8qyGVaGSr) in May 2012:
2. This was not an oversight: Douglas Crockford [wrote on this](https://news.ycombinator.com/item?id=3912149) in May 2012:
> I removed comments from JSON because I saw people were using them to hold parsing directives, a practice which would have destroyed interoperability. I know that the lack of comments makes some people sad, but it shouldn't.
>
@@ -1801,7 +1849,7 @@ This library does not support comments by default. It does so for three reasons:
3. It is dangerous for interoperability if some libraries would add comment support while others don't. Please check [The Harmful Consequences of the Robustness Principle](https://tools.ietf.org/html/draft-iab-protocol-maintenance-01) on this.
However, you can set set parameter `ignore_comments` to true in the `parse` function to ignore `//` or `/* */` comments. Comments will then be treated as whitespace.
However, you can set parameter `ignore_comments` to true in the `parse` function to ignore `//` or `/* */` comments. Comments will then be treated as whitespace.
### Trailing commas
@@ -1851,7 +1899,7 @@ ctest --output-on-failure
Note that during the `ctest` stage, several JSON test files are downloaded from an [external repository](https://github.com/nlohmann/json_test_data). If policies forbid downloading artifacts during testing, you can download the files yourself and pass the directory with the test files via `-DJSON_TestDataDirectory=path` to CMake. Then, no Internet connectivity is required. See [issue #2189](https://github.com/nlohmann/json/issues/2189) for more information.
If the test suite is not found, several test suites will fail like this:
If the testdata is not found, several test suites will fail like this:
In case you have downloaded the library rather than checked out the code via Git, test `cmake_fetch_content_configure` will fail. Please execute `ctest -LE git_required` to skip these tests. See [issue #2189](https://github.com/nlohmann/json/issues/2189) for more information.
Some tests are requiring network to be properly execute. They are labeled as `git_required`. Please execute `ctest -LE git_required` to skip these tests. See [issue #4851](https://github.com/nlohmann/json/issues/4851) for more information.
Some tests change the installed files and hence make the whole process not reproducible. Please execute `ctest -LE not_reproducible` to skip these tests. See [issue #2324](https://github.com/nlohmann/json/issues/2324) for more information. Furthermore, assertions must be switched off to ensure reproducible builds (see [discussion 4494](https://github.com/nlohmann/json/discussions/4494)).
Note you need to call `cmake -LE "not_reproducible|git_required"` to exclude both labels. See [issue #2596](https://github.com/nlohmann/json/issues/2596) for more information.
| `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version). |
| `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version). On HP aCC compilers, `compiler` is instead the plain string `hp`. |
| `copyright` | The copyright line for the library as string. |
| `name` | The name of the library as string. |
| `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`. |
@@ -32,7 +32,9 @@ Strong guarantee: if an exception is thrown, there are no changes in the JSON va
could not be resolved successfully in the current JSON value; example: `"key baz not found"`.
- Throws [`out_of_range.405`](../../home/exceptions.md#jsonexceptionout_of_range405) if JSON pointer has no parent
("add", "remove", "move")
- Throws [`out_of_range.501`](../../home/exceptions.md#jsonexceptionother_error501) if "test" operation was
- Throws [`out_of_range.411`](../../home/exceptions.md#jsonexceptionout_of_range411) if an "add" operation's target
location has a parent that is neither an object nor an array.
- Throws [`other_error.501`](../../home/exceptions.md#jsonexceptionother_error501) if "test" operation was
unsuccessful.
## Complexity
@@ -71,3 +73,5 @@ is thrown. In any case, the original value is not changed: the patch is applied
## Version history
- Added in version 2.0.0.
- Added [`out_of_range.411`](../../home/exceptions.md#jsonexceptionout_of_range411) and stopped relying on an internal assertion when an "add" operation's
target location has a non-object/non-array parent in version 3.12.x.
- [merge_patch](merge_patch.md) applies a JSON Merge Patch
## Version history
- Added in version 3.11.0.
- Added [`out_of_range.411`](../../home/exceptions.md#jsonexceptionout_of_range411) and stopped relying on an internal assertion when an "add" operation's
target location has a non-object/non-array parent in version 3.12.x.
@@ -25,6 +25,10 @@ The function can throw the following exceptions:
- Throws [`type_error.314`](../../home/exceptions.md#jsonexceptiontype_error314) if value is not an object
- Throws [`type_error.315`](../../home/exceptions.md#jsonexceptiontype_error315) if object values are not primitive
- Throws [`type_error.313`](../../home/exceptions.md#jsonexceptiontype_error313) if a key (JSON pointer) leads to a
conflicting nesting; example: `"invalid value to unflatten"`
- Throws [`parse_error.109`](../../home/exceptions.md#jsonexceptionparse_error109) if an array index in a key is not a
number; example: `"array index 'one' is not a number"`
## Complexity
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.