mirror of
https://github.com/nlohmann/json.git
synced 2026-07-10 12:35:09 +00:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 10d18792bd | |||
| 8557b661ab | |||
| 48face7a20 | |||
| 68c87ad9de |
@@ -234,22 +234,11 @@ jobs:
|
||||
|
||||
ci_cuda_example:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
# 11.8.0: newest pre-C++20 CUDA release, exercises the C++17 fallback
|
||||
# path (tests/cuda_example/CMakeLists.txt picks the standard per nvcc
|
||||
# version); 12.1.1: permanent regression guard for #3907 (nvcc 12.0/12.1
|
||||
# choke on enable_borrowed_range at C++20, fixed in 12.2); 12.6.3: recent
|
||||
# CUDA/C++20 coverage.
|
||||
cuda: ['11.8.0', '12.1.1', '12.6.3']
|
||||
container: nvidia/cuda:${{ matrix.cuda }}-devel-ubuntu22.04
|
||||
container: ghcr.io/nlohmann/json-ci:v2.4.0
|
||||
steps:
|
||||
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Get latest CMake and ninja
|
||||
uses: lukka/get-cmake@f5b8fbb4d77cec1acc5a5f9f0df4beffaf5d98d9 # v4.3.4
|
||||
- name: Run CMake
|
||||
run: cmake -S . -B build -DJSON_CI=On
|
||||
- name: Build
|
||||
|
||||
+2
-6
@@ -669,6 +669,7 @@ add_custom_target(ci_test_compiler_default
|
||||
add_custom_target(ci_cuda_example
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DCMAKE_BUILD_TYPE=Debug -GNinja
|
||||
-DCMAKE_CUDA_HOST_COMPILER=g++-8
|
||||
-S${PROJECT_SOURCE_DIR}/tests/cuda_example -B${PROJECT_BINARY_DIR}/build_cuda_example
|
||||
COMMAND ${CMAKE_COMMAND} --build ${PROJECT_BINARY_DIR}/build_cuda_example
|
||||
)
|
||||
@@ -719,11 +720,6 @@ add_custom_target(ci_icpx
|
||||
# to zero and does not honor NaN ordering; -Kieee restores strict IEEE 754 behavior
|
||||
# (needed for the dtoa/grisu and NaN-comparison code paths).
|
||||
#
|
||||
# -tp=px pins the target processor to the generic x86-64 baseline (SSE2-only) to avoid
|
||||
# a nvc++ 25.5 / LLVM issue: when nvc++ auto-detects -tp from the runner's CPU (e.g. -tp znver4),
|
||||
# certain attribute combinations trigger an llc instruction-selection crash on std::ldexp<unsigned>.
|
||||
# Pinning to px removes this variability and is robust to future llc/nvc++ updates.
|
||||
#
|
||||
# The following tests are excluded as they trigger known nvc++ 25.5 defects (not
|
||||
# library bugs); see https://github.com/nlohmann/json for tracking. Only the
|
||||
# affected language-standard variants are excluded so coverage is otherwise kept:
|
||||
@@ -737,7 +733,7 @@ add_custom_target(ci_nvhpc
|
||||
COMMAND ${CMAKE_COMMAND}
|
||||
-DCMAKE_BUILD_TYPE=Debug -GNinja
|
||||
-DCMAKE_C_COMPILER=nvc -DCMAKE_CXX_COMPILER=nvc++
|
||||
-DCMAKE_CXX_FLAGS="-Kieee;-tp=px"
|
||||
-DCMAKE_CXX_FLAGS=-Kieee
|
||||
-DJSON_BuildTests=ON -DJSON_FastTests=ON
|
||||
-S${PROJECT_SOURCE_DIR} -B${PROJECT_BINARY_DIR}/build_nvhpc
|
||||
COMMAND ${CMAKE_COMMAND} --build ${PROJECT_BINARY_DIR}/build_nvhpc
|
||||
|
||||
@@ -5,11 +5,8 @@
|
||||
# -Wno-extra-semi-stmt The library uses assert which triggers this warning.
|
||||
# -Wno-padded We do not care about padding warnings.
|
||||
# -Wno-covered-switch-default All switches list all cases and a default case.
|
||||
# -Wno-unsafe-buffer-usage Pervasive: the library's own low-level numeric/buffer code
|
||||
# (to_chars, serializer, lexer, binary reader/writer, input
|
||||
# adapters, json_pointer) plus vendored Doctest itself (~208
|
||||
# distinct sites measured 2026-07-08 on clang trunk) all use
|
||||
# raw pointer arithmetic / libc string calls by necessity.
|
||||
# -Wno-unsafe-buffer-usage Otherwise Doctest would not compile.
|
||||
# -Wno-missing-noreturn We found no way to silence this warning otherwise, see PR #4871
|
||||
|
||||
set(CLANG_CXXFLAGS
|
||||
-Werror
|
||||
@@ -21,4 +18,5 @@ set(CLANG_CXXFLAGS
|
||||
-Wno-padded
|
||||
-Wno-covered-switch-default
|
||||
-Wno-unsafe-buffer-usage
|
||||
-Wno-missing-noreturn
|
||||
)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"archive": "JSON_for_Modern_C++.tgz",
|
||||
"author": {
|
||||
"name": "Niels Lohmann",
|
||||
"link": "https://nlohmann.me"
|
||||
"link": "https://twitter.com/nlohmann"
|
||||
},
|
||||
"aliases": ["nlohmann/json"]
|
||||
}
|
||||
|
||||
@@ -109,7 +109,7 @@ A UTF-8 byte order mark is silently ignored.
|
||||
- Added in version 3.0.0.
|
||||
- Ignoring comments via `ignore_comments` added in version 3.9.0.
|
||||
- Changed [runtime assertion](../../features/assertions.md) in case of `FILE*` null pointers to exception in version 3.12.0.
|
||||
- Added `ignore_trailing_commas` in version 3.13.0.
|
||||
- Added `ignore_trailing_commas` in version 3.12.x.
|
||||
|
||||
!!! warning "Deprecation"
|
||||
|
||||
|
||||
@@ -115,22 +115,7 @@ basic_json(basic_json&& other) noexcept;
|
||||
|
||||
Function [`array()`](array.md) and [`object()`](object.md) force array and object creation from initializer lists,
|
||||
respectively.
|
||||
|
||||
!!! warning "Brace initialization yields arrays"
|
||||
|
||||
Because this constructor takes an `initializer_list_t`, brace-initializing a `json`/`ordered_json` from
|
||||
another `json` value wraps it in a single-element array rather than copying it:
|
||||
|
||||
```cpp
|
||||
json j1 = "hello";
|
||||
json j2{j1}; // [!] j2 is ["hello"], NOT a copy of j1
|
||||
json j3(j1); // j3 is "hello" -- parentheses copy as expected
|
||||
```
|
||||
|
||||
See the FAQ entry on [brace initialization](../../home/faq.md#brace-initialization-yields-arrays) for the
|
||||
full explanation, an opt-in macro to change this behavior, and how to explicitly create a single-element
|
||||
array (`json::array({value})`) if that is what you want.
|
||||
|
||||
|
||||
6. Constructs a JSON array value by creating `cnt` copies of a passed value. In case `cnt` is `0`, an empty array is
|
||||
created.
|
||||
|
||||
|
||||
@@ -37,14 +37,6 @@ represent a byte array in modern C++.
|
||||
`BinaryType`
|
||||
: container type to store arrays
|
||||
|
||||
Although not formally expressed as a C++ concept, `BinaryType` must be default-constructible,
|
||||
copy/move-constructible, and support `push_back()`, `.data()`, and `.size()`, because
|
||||
[`byte_container_with_subtype`](../byte_container_with_subtype/index.md) derives directly from it. Its
|
||||
`value_type` must additionally be exactly one byte wide (e.g., `std::uint8_t`/`char`/`std::byte`): the binary
|
||||
serializers (CBOR, MessagePack, BSON, UBJSON) read and write the container's raw bytes via
|
||||
`reinterpret_cast`, which is only correct for byte-sized elements -- a container like
|
||||
`#!cpp std::vector<std::intptr_t>` will not work as `BinaryType`.
|
||||
|
||||
## Notes
|
||||
|
||||
#### Default type
|
||||
|
||||
@@ -92,4 +92,4 @@ std::string format_as(const BasicJsonType& j)
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.13.0.
|
||||
- Added in version 3.12.x.
|
||||
|
||||
@@ -114,13 +114,6 @@ overload (3).
|
||||
See [Number conversion](../../features/types/number_handling.md#number-conversion)
|
||||
for more information.
|
||||
|
||||
!!! note "`std::optional` conversions"
|
||||
|
||||
Prior to version 3.13.0, `#!cpp get<std::optional<T>>()` (and other conversions to `std::optional<T>`) failed to
|
||||
compile in every configuration, due to an internal implementation bug that made the `from_json` overload for
|
||||
`std::optional` unreachable regardless of the [`JSON_USE_IMPLICIT_CONVERSIONS`](../macros/json_use_implicit_conversions.md)
|
||||
setting. This has been fixed.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
@@ -46,17 +46,6 @@ for (auto& [key, val] : j_object.items())
|
||||
}
|
||||
```
|
||||
|
||||
If you need to name the type of the dereferenced element explicitly (e.g., to write a standalone function that
|
||||
takes it as a parameter, or to use `items()` with `std::for_each`), use `decltype`:
|
||||
|
||||
```cpp
|
||||
using element_type = decltype(*j_object.items().begin());
|
||||
```
|
||||
|
||||
The per-element type (`iteration_proxy_value`) lives in the library's internal `detail` namespace and is
|
||||
intentionally unspecified as a stable, named type -- `decltype` is the supported way to obtain it, but its exact
|
||||
name/definition may change between versions.
|
||||
|
||||
## Return value
|
||||
|
||||
iteration proxy object wrapping the current value with an interface to use in range-based for loops
|
||||
|
||||
@@ -63,8 +63,7 @@ behavior:
|
||||
object will agree on the name-value mappings.
|
||||
- When the names within an object are not unique, it is unspecified which one of the values for a given key will be
|
||||
chosen. For instance, `#!json {"key": 2, "key": 1}` could be equal to either `#!json {"key": 1}` or
|
||||
`#!json {"key": 2}`. To reject duplicate keys instead of silently resolving them one way or another, see
|
||||
[this parsing recipe](../../features/parsing/parser_callbacks.md#recipe-rejecting-duplicate-object-keys).
|
||||
`#!json {"key": 2}`.
|
||||
- Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see
|
||||
[`dump`](dump.md)) in this order. For instance, `#!json {"b": 1, "a": 2}` and `#!json {"a": 2, "b": 1}` will be stored
|
||||
and serialized as `#!json {"a": 2, "b": 1}`.
|
||||
|
||||
@@ -124,15 +124,6 @@ Strong exception safety: if an exception occurs, the original value stays intact
|
||||
filled with `#!json null`.
|
||||
- The special value `-` is treated as a synonym for the index past the end.
|
||||
|
||||
!!! note "Creating intermediate levels that don't exist yet"
|
||||
|
||||
When the JSON pointer traverses intermediate levels that don't exist at all yet (not just a missing
|
||||
leaf), each missing level is created as an array or an object depending on whether the corresponding
|
||||
pointer token parses as a non-negative integer: a numeric token creates an array, a non-numeric token
|
||||
creates an object. For example, on an initially `#!json null` value, `/foo/0/0/0` creates nested arrays,
|
||||
while `/foo/one/one/one` creates nested objects. This is not specified by the JSON Pointer RFC; it is
|
||||
this library's own, intentional disambiguation rule. See also [JSON Pointer](../../features/json_pointer.md).
|
||||
|
||||
## Examples
|
||||
|
||||
??? example "Example: (1) access specified array element"
|
||||
@@ -260,6 +251,5 @@ Strong exception safety: if an exception occurs, the original value stays intact
|
||||
1. Added in version 1.0.0.
|
||||
2. Added in version 1.0.0. Added overloads for `T* key` in version 1.1.0. Removed overloads for `T* key` (replaced by 3)
|
||||
in version 3.11.0.
|
||||
3. Added in version 3.11.0. Fixed in version 3.13.0 to consistently accept `std::string_view`-convertible keys, as
|
||||
already supported by [`at`](at.md), [`value`](value.md), [`find`](find.md), and other lookup functions.
|
||||
3. Added in version 3.11.0.
|
||||
4. Added in version 2.0.0.
|
||||
|
||||
@@ -19,8 +19,10 @@ class basic_json {
|
||||
};
|
||||
```
|
||||
|
||||
1. Compares two JSON values for inequality. Returns `#!cpp !(lhs == rhs)` (until C++20) or `#!cpp !(*this == rhs)` (since C++20).
|
||||
- This means the comparison is simply the logical negation of `operator==`, including for special values like `NaN` and `discarded`.
|
||||
1. Compares two JSON values for inequality according to the following rules:
|
||||
- The comparison always yields `#!cpp false` if (1) either operand is discarded, or (2) either operand is `NaN` and
|
||||
the other operand is either `NaN` or any other number.
|
||||
- Otherwise, returns the result of `#!cpp !(lhs == rhs)` (until C++20) or `#!cpp !(*this == rhs)` (since C++20).
|
||||
|
||||
2. Compares a JSON value and a scalar or a scalar and a JSON value for inequality by converting the scalar to a JSON
|
||||
value and comparing both JSON values according to 1.
|
||||
@@ -52,12 +54,13 @@ Linear.
|
||||
|
||||
## Notes
|
||||
|
||||
!!! note "Comparing `NaN` and `discarded`"
|
||||
!!! note "Comparing `NaN`"
|
||||
|
||||
Since `operator!=` is defined as `!(a == b)`, the behavior for special values follows that of `operator==`:
|
||||
|
||||
- For `NaN` values: `NaN == NaN` yields `#!cpp false`, so `NaN != NaN` yields `#!cpp true`.
|
||||
- For `discarded` values: `discarded == x` yields `#!cpp false` for any `x`, so `discarded != x` yields `#!cpp true`.
|
||||
`NaN` values are unordered within the domain of numbers.
|
||||
The following comparisons all yield `#!cpp false`:
|
||||
1. Comparing a `NaN` with itself.
|
||||
2. Comparing a `NaN` with another `NaN`.
|
||||
3. Comparing a `NaN` and any other number.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -91,7 +94,5 @@ Linear.
|
||||
|
||||
## Version history
|
||||
|
||||
1. Added in version 1.0.0. Added C++20 member functions in version 3.11.0. Changed in version 3.13.0 to remove
|
||||
special-casing for `NaN` and `discarded` values; `operator!=` now consistently means `!(a == b)`.
|
||||
2. Added in version 1.0.0. Added C++20 member functions in version 3.11.0. Changed in version 3.13.0 to remove
|
||||
special-casing for `NaN` and `discarded` values; `operator!=` now consistently means `!(a == b)`.
|
||||
1. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.
|
||||
2. Added in version 1.0.0. Added C++20 member functions in version 3.11.0.
|
||||
|
||||
@@ -235,7 +235,7 @@ Invalid Unicode escapes and unpaired surrogates in the input are reported as
|
||||
- Overload for contiguous containers (1) added in version 2.0.3.
|
||||
- Ignoring comments via `ignore_comments` added in version 3.9.0.
|
||||
- Changed [runtime assertion](../../features/assertions.md) in case of `FILE*` null pointers to exception in version 3.12.0.
|
||||
- Added `ignore_trailing_commas` in version 3.13.0.
|
||||
- Added `ignore_trailing_commas` in version 3.12.x.
|
||||
|
||||
!!! warning "Deprecation"
|
||||
|
||||
|
||||
@@ -74,4 +74,4 @@ is thrown. In any case, the original value is not changed: the patch is applied
|
||||
|
||||
- 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.13.0.
|
||||
target location has a non-object/non-array parent in version 3.12.x.
|
||||
|
||||
@@ -71,4 +71,4 @@ function throws an exception.
|
||||
|
||||
- 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.13.0.
|
||||
target location has a non-object/non-array parent in version 3.12.x.
|
||||
|
||||
@@ -126,7 +126,7 @@ A UTF-8 byte order mark is silently ignored.
|
||||
|
||||
- Added in version 3.2.0.
|
||||
- Ignoring comments via `ignore_comments` added in version 3.9.0.
|
||||
- Added `ignore_trailing_commas` in version 3.13.0.
|
||||
- Added `ignore_trailing_commas` in version 3.12.x.
|
||||
|
||||
!!! warning "Deprecation"
|
||||
|
||||
|
||||
@@ -54,4 +54,4 @@ provides `<format>`, controlled by the [`JSON_HAS_STD_FORMAT`](../macros/json_ha
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.13.0.
|
||||
- Added in version 3.12.x.
|
||||
|
||||
@@ -6,9 +6,18 @@ namespace std {
|
||||
}
|
||||
```
|
||||
|
||||
Return a hash value for a JSON object. The hash function tries to rely on `std::hash` where possible. Furthermore, the
|
||||
type of the JSON value is taken into account to have different hash values for `#!json null`, `#!cpp 0`, `#!cpp 0U`, and
|
||||
`#!cpp false`, etc.
|
||||
Return a hash value for a JSON object. The hash function tries to rely on `std::hash` where possible. To satisfy the
|
||||
`std::hash` contract, numeric JSON values that compare equal must hash to the same value. This means:
|
||||
|
||||
- `json(42)`, `json(42u)`, and `json(42.0)` all hash to the same value
|
||||
- `json(0)`, `json(0u)`, and `json(0.0)` all hash to the same value
|
||||
|
||||
Different types hash differently for non-numeric types (e.g., `#!json null`, `#!cpp false`, and strings all have distinct hashes).
|
||||
|
||||
**Edge case:** For very large integers outside the exact representable range of the floating-point type (beyond ~2^53 for
|
||||
typical `double`), the hash values for integer and floating-point values may differ, even if the floating-point value
|
||||
was obtained by casting the integer (due to precision loss). This is a documented limitation arising from how the
|
||||
comparison operator normalizes numeric types.
|
||||
|
||||
## Examples
|
||||
|
||||
|
||||
@@ -18,11 +18,6 @@ JSON class into byte-sized characters during deserialization.
|
||||
: the container to store strings (e.g., `std::string`). Note this container is used for keys/names in objects, see
|
||||
[object_t](object_t.md).
|
||||
|
||||
`StringType` must have a `char`-compatible `value_type`: the library relies on UTF-8/`char`-based storage and
|
||||
processing internally, so `std::wstring`, `std::u16string`, and `std::u32string` are **not** valid choices for
|
||||
`StringType`. To work with wide-character data, convert it to/from UTF-8 at the boundary instead -- see the
|
||||
FAQ's [wide string handling](../../home/faq.md#wide-string-handling) section for a conversion recipe.
|
||||
|
||||
## Notes
|
||||
|
||||
#### Default type
|
||||
|
||||
@@ -21,12 +21,6 @@ a string representation of the type ([`value_t`](value_t.md)):
|
||||
| array | `"array"` |
|
||||
| binary | `"binary"` |
|
||||
| discarded | `"discarded"` |
|
||||
| invalid (corrupted value) | `"invalid"` |
|
||||
|
||||
!!! note "The \"invalid\" type"
|
||||
|
||||
The `"invalid"` return value indicates a corrupted JSON value — this can occur if an enum value falls outside the
|
||||
range of valid `value_t` values. This is useful for diagnosing data corruption or internal errors.
|
||||
|
||||
## Exception safety
|
||||
|
||||
@@ -58,4 +52,3 @@ Constant.
|
||||
- Part of the public API version since 2.1.0.
|
||||
- Changed return value to `const char*` and added `noexcept` in version 3.0.0.
|
||||
- Added support for binary type in version 3.8.0.
|
||||
- Added `"invalid"` return value for corrupted JSON values in version 3.13.0.
|
||||
|
||||
@@ -17,8 +17,6 @@ ValueType value(const json_pointer& ptr,
|
||||
const ValueType& default_value) const;
|
||||
```
|
||||
|
||||
This is equivalent to Python's `dict.get(key, default)`.
|
||||
|
||||
1. Returns either a copy of an object's element at the specified key `key` or a given default value if no element with
|
||||
key `key` exists.
|
||||
|
||||
@@ -186,6 +184,4 @@ changes to any JSON value.
|
||||
|
||||
1. Added in version 1.0.0. Changed parameter `default_value` type from `const ValueType&` to `ValueType&&` in version 3.11.0.
|
||||
2. Added in version 3.11.0. Made `ValueType` the first template parameter in version 3.11.2.
|
||||
3. Added in version 2.0.2. Extended to work with arrays in version 3.13.0, including fixing an issue where resolving
|
||||
`ptr` through an array unexpectedly threw `out_of_range` instead of returning the resolved element (or
|
||||
`default_value`, as documented).
|
||||
3. Added in version 2.0.2. Extended to work with arrays in version 3.12.x.
|
||||
|
||||
@@ -36,4 +36,4 @@ Constant.
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.13.0.
|
||||
- Added in version 3.12.x.
|
||||
|
||||
@@ -32,4 +32,4 @@ Linear in the number of reference tokens in the `json_pointer`.
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.13.0.
|
||||
- Added in version 3.12.x.
|
||||
|
||||
@@ -35,4 +35,4 @@ Linear in the number of reference tokens in the `json_pointer`.
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.13.0.
|
||||
- Added in version 3.12.x.
|
||||
|
||||
@@ -92,4 +92,4 @@ The default value is `0` (disabled — existing behavior is preserved).
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.13.0.
|
||||
- Added in version 3.12.x.
|
||||
|
||||
@@ -44,4 +44,4 @@ The default value is detected based on preprocessor macros such as `#!cpp __cplu
|
||||
|
||||
- Added in version 3.10.5.
|
||||
- Added `JSON_HAS_CPP_23` in version 3.12.0.
|
||||
- Added `JSON_HAS_CPP_26` in version 3.13.0.
|
||||
- Added `JSON_HAS_CPP_26` in version 3.12.x.
|
||||
|
||||
@@ -19,20 +19,6 @@ The default value is detected based on the preprocessor macros `#!cpp __cpp_lib_
|
||||
`#!cpp __cpp_lib_experimental_filesystem`, `#!cpp __has_include(<filesystem>)`, or
|
||||
`#!cpp __has_include(<experimental/filesystem>)`.
|
||||
|
||||
!!! info "Known compiler/stdlib exclusions"
|
||||
|
||||
Even when the feature-test macro indicates filesystem support is available, the library disables it on the following broken toolchains:
|
||||
|
||||
- **MinGW + GCC 8** — disabled entirely (broken `std::filesystem` implementation; [MinGW-w64 bug 737](https://sourceforge.net/p/mingw-w64/bugs/737/))
|
||||
- **GCC (non-Clang) < 8** — disabled (no filesystem support)
|
||||
- **Clang < 7** — disabled (no filesystem support)
|
||||
- **MSVC < 19.14** — disabled (no filesystem support)
|
||||
- **iOS < 13** — disabled (no filesystem support)
|
||||
- **macOS < Catalina (10.15)** — disabled (no filesystem support)
|
||||
|
||||
If `JSON_HAS_FILESYSTEM` or `JSON_HAS_EXPERIMENTAL_FILESYSTEM` is `0` despite `__cpp_lib_filesystem` being defined, one
|
||||
of the exclusions above likely applies to your toolchain.
|
||||
|
||||
## Notes
|
||||
|
||||
- Note that older compilers or older versions of libstdc++ also require the library `stdc++fs` to be linked to for
|
||||
|
||||
@@ -13,20 +13,6 @@ The default value is detected based on the preprocessor macro `#!cpp __cpp_lib_r
|
||||
|
||||
When the macro is not defined, the library will define it to its default value.
|
||||
|
||||
!!! info "Known compiler/stdlib exclusions"
|
||||
|
||||
Even when the feature-test macro `__cpp_lib_ranges` indicates ranges support is available, the library disables it on
|
||||
the following incomplete or broken toolchains:
|
||||
|
||||
- **GCC 11.1.0** — disabled (the shipped `<ranges>` header has a syntax error; [issue #4440](https://github.com/nlohmann/json/issues/4440))
|
||||
- **libstdc++ < 11** — disabled (incomplete C++20 ranges support; [issue #4440](https://github.com/nlohmann/json/issues/4440))
|
||||
- **Clang < 16 with libstdc++** — disabled (incomplete ranges support; [issue #4440](https://github.com/nlohmann/json/issues/4440))
|
||||
- **libc++ < 160000** — disabled (incomplete C++20 ranges support; [issue #4440](https://github.com/nlohmann/json/issues/4440))
|
||||
- **nvcc (CUDA) 12.0.x and 12.1.x** — disabled (the `enable_borrowed_range` variable-template syntax triggers a parse error
|
||||
under these two toolkit versions; fixed in CUDA 12.2; [issue #3907](https://github.com/nlohmann/json/issues/3907))
|
||||
|
||||
If `JSON_HAS_RANGES` is `0` despite `__cpp_lib_ranges` being defined, one of the exclusions above likely applies to your toolchain.
|
||||
|
||||
## Examples
|
||||
|
||||
??? example
|
||||
|
||||
@@ -38,4 +38,4 @@ When the macro is not defined, the library will define it to its default value.
|
||||
|
||||
## Version history
|
||||
|
||||
- Added in version 3.13.0.
|
||||
- Added in version 3.12.x.
|
||||
|
||||
@@ -62,9 +62,6 @@ See the examples below for the concrete generated code.
|
||||
|
||||
- The current implementation is limited to at most 63 member variables. If you want to serialize/deserialize types
|
||||
with more than 63 member variables, you need to define the `to_json`/`from_json` functions manually.
|
||||
- These macros always produce object-style (named-key) JSON, one key per member. There is no macro variant
|
||||
that serializes a struct's members positionally into a JSON array; for that, write `to_json`/`from_json` by
|
||||
hand, building/reading a `json::array()` of the members in order.
|
||||
|
||||
## Examples
|
||||
|
||||
|
||||
@@ -63,9 +63,6 @@ See the examples below for the concrete generated code.
|
||||
|
||||
- The current implementation is limited to at most 63 member variables. If you want to serialize/deserialize types
|
||||
with more than 63 member variables, you need to define the `to_json`/`from_json` functions manually.
|
||||
- These macros always produce object-style (named-key) JSON, one key per member. There is no macro variant
|
||||
that serializes a struct's members positionally into a JSON array; for that, write `to_json`/`from_json` by
|
||||
hand, building/reading a `json::array()` of the members in order.
|
||||
|
||||
## Examples
|
||||
|
||||
|
||||
@@ -75,4 +75,4 @@ For further information please refer to the corresponding macros without `WITH_N
|
||||
|
||||
## Version history
|
||||
|
||||
1. Added in version 3.13.0.
|
||||
1. Added in version 3.12.x.
|
||||
|
||||
@@ -102,4 +102,4 @@ inline void from_json(const BasicJsonType& j, type& e);
|
||||
|
||||
## Version history
|
||||
|
||||
Added in version 3.13.0.
|
||||
Added in version 3.12.x.
|
||||
|
||||
@@ -33,18 +33,6 @@ A UTF-8 byte order mark is silently ignored.
|
||||
Invalid Unicode escapes and unpaired surrogates in the input are reported as
|
||||
[`parse_error.101`](../home/exceptions.md#jsonexceptionparse_error101) with a detailed message.
|
||||
|
||||
`operator>>` parses exactly one JSON value and leaves the stream positioned right after it, so it can be called
|
||||
repeatedly to read a sequence of concatenated JSON values from the same stream:
|
||||
|
||||
```cpp
|
||||
json j1, j2;
|
||||
input >> j1; // parses the first value, stream now positioned right after it
|
||||
input >> j2; // parses the next value
|
||||
```
|
||||
|
||||
Note this does **not** work for [JSON Lines](../features/parsing/json_lines.md) (newline-delimited JSON) input --
|
||||
see that page for why and for the recommended alternative.
|
||||
|
||||
!!! warning "Deprecation"
|
||||
|
||||
This function replaces function `#!cpp std::istream& operator<<(basic_json& j, std::istream& i)` which has
|
||||
|
||||
@@ -64,4 +64,4 @@ Linear.
|
||||
|
||||
- Added in version 1.0.0.
|
||||
- Moved to namespace `nlohmann::literals::json_literals` in 3.11.0.
|
||||
- Added `char8_t*` overload in 3.13.0.
|
||||
- Added `char8_t*` overload in 3.12.x.
|
||||
|
||||
@@ -63,4 +63,4 @@ Linear.
|
||||
|
||||
- Added in version 2.0.0.
|
||||
- Moved to namespace `nlohmann::literals::json_literals` in 3.11.0.
|
||||
- Added `char8_t*` overload in 3.13.0.
|
||||
- Added `char8_t*` overload in 3.12.x.
|
||||
|
||||
@@ -10,10 +10,6 @@ violations will result in a failed build.
|
||||
|
||||
Any compiler with complete C++11 support can compile the library without warnings.
|
||||
|
||||
Note: C++20 modules support may hit compiler-specific issues not covered by the general compiler matrix below. See [Modules](../features/modules.md#known-issues) for known issues and workarounds.
|
||||
|
||||
Note: Some modern features (like C++20 ranges or filesystem support) may be disabled on specific broken or incomplete toolchains even when standard feature-test macros indicate support. See [`JSON_HAS_RANGES`](../api/macros/json_has_ranges.md) and [`JSON_HAS_FILESYSTEM`](../api/macros/json_has_filesystem.md) for details on known exclusions.
|
||||
|
||||
- [x] The library is compiled with 50+ different C++ compilers with different operating systems and platforms,
|
||||
including the oldest versions known to compile the library.
|
||||
|
||||
@@ -66,9 +62,7 @@ Note: Some modern features (like C++20 ranges or filesystem support) may be disa
|
||||
| Clang 20.1.1 | x86_64 | Ubuntu 22.04.1 LTS | GitHub |
|
||||
| Clang 20.1.8 with GNU-like command-line | x86_64 | Windows Server 2022 (Build 20348) | GitHub |
|
||||
| Clang 21.1.8 | x86_64 | Ubuntu 22.04.1 LTS | GitHub |
|
||||
| CUDA 11.8.0 (nvcc) | x86_64 | Ubuntu 22.04 LTS | GitHub |
|
||||
| CUDA 12.1.1 (nvcc) | x86_64 | Ubuntu 22.04 LTS | GitHub |
|
||||
| CUDA 12.6.3 (nvcc) | x86_64 | Ubuntu 22.04 LTS | GitHub |
|
||||
| CUDA 11.0.221 (nvcc) | x86_64 | Ubuntu 20.04 LTS | GitHub |
|
||||
| Emscripten 4.0.6 | x86_64 | Ubuntu 22.04.1 LTS | GitHub |
|
||||
| GNU 4.8.5 | x86_64 | Ubuntu 22.04.1 LTS | GitHub |
|
||||
| GNU 4.9.3 | x86_64 | Ubuntu 22.04.1 LTS | GitHub |
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
#include <iostream>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
using json = nlohmann::json;
|
||||
|
||||
json parse_strict(const std::string& input)
|
||||
{
|
||||
// one key set per nesting depth, reused across sibling objects
|
||||
std::vector<std::unordered_set<std::string>> keys;
|
||||
|
||||
auto reject_duplicate_keys = [&](int depth, json::parse_event_t event, json & parsed)
|
||||
{
|
||||
if (event == json::parse_event_t::object_start)
|
||||
{
|
||||
// keys of this object are reported at depth+1 (see the event table above)
|
||||
const auto child_depth = static_cast<std::size_t>(depth) + 1;
|
||||
if (keys.size() <= child_depth)
|
||||
{
|
||||
keys.resize(child_depth + 1);
|
||||
}
|
||||
keys[child_depth].clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (event == json::parse_event_t::key)
|
||||
{
|
||||
auto& seen = keys[static_cast<std::size_t>(depth)];
|
||||
const auto& key = parsed.get_ref<const std::string&>();
|
||||
if (!seen.insert(key).second)
|
||||
{
|
||||
throw std::runtime_error("duplicate JSON object key: " + key);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
return json::parse(input, reject_duplicate_keys);
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
// parsing succeeds when all keys are unique
|
||||
json j = parse_strict(R"({"one": 1, "two": 2})");
|
||||
std::cout << j << '\n';
|
||||
|
||||
// parsing throws when a key is repeated
|
||||
try
|
||||
{
|
||||
parse_strict(R"({"one": 1, "one": 2})");
|
||||
}
|
||||
catch (const std::exception& e)
|
||||
{
|
||||
std::cout << e.what() << '\n';
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
{"one":1,"two":2}
|
||||
duplicate JSON object key: one
|
||||
@@ -11,6 +11,7 @@ int main()
|
||||
<< "hash(false) = " << std::hash<json> {}(json(false)) << '\n'
|
||||
<< "hash(0) = " << std::hash<json> {}(json(0)) << '\n'
|
||||
<< "hash(0U) = " << std::hash<json> {}(json(0U)) << '\n'
|
||||
<< "hash(0.0) = " << std::hash<json> {}(json(0.0)) << '\n'
|
||||
<< "hash(\"\") = " << std::hash<json> {}(json("")) << '\n'
|
||||
<< "hash({}) = " << std::hash<json> {}(json::object()) << '\n'
|
||||
<< "hash([]) = " << std::hash<json> {}(json::array()) << '\n'
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
hash(null) = 2654435769
|
||||
hash(false) = 2654436030
|
||||
hash(0) = 2654436095
|
||||
hash(0U) = 2654436156
|
||||
hash("") = 6142509191626859748
|
||||
hash(0) = 2654436221
|
||||
hash(0U) = 2654436221
|
||||
hash(0.0) = 2654436221
|
||||
hash("") = 11160318156688833227
|
||||
hash({}) = 2654435832
|
||||
hash([]) = 2654435899
|
||||
hash({"hello": "world"}) = 4469488738203676328
|
||||
hash({"hello": "world"}) = 3701319991624763853
|
||||
|
||||
@@ -180,49 +180,6 @@ For _derived_ classes and structs, use the following macros
|
||||
}
|
||||
```
|
||||
|
||||
!!! warning "Overriding conversions for natively-supported types"
|
||||
|
||||
The library already provides built-in `to_json`/`from_json` conversions for STL containers such as
|
||||
`std::vector`, `std::array`, and `std::map`. Defining your own free-function `to_json`/`from_json` overload
|
||||
for one of these container types directly (instead of for your own type) can conflict with the built-in
|
||||
overload during overload resolution, producing compiler errors ("no matching overloaded function",
|
||||
"call is ambiguous") that vary by compiler and library version. If you need different conversion behavior
|
||||
for a container type the library already handles, wrap it in your own type (or use `adl_serializer`
|
||||
specialization, as shown [above](#how-do-i-convert-third-party-types) for `boost::optional`) instead of
|
||||
trying to re-specialize `to_json`/`from_json` for the container type itself.
|
||||
|
||||
!!! warning "Raw C-style arrays"
|
||||
|
||||
Members declared as raw C-style arrays (e.g., `char buf[1024]`) do not round-trip safely through
|
||||
`NLOHMANN_DEFINE_TYPE_*` macros or the default (de)serializers: `to_json` serializes any `char` array as a
|
||||
JSON *string* (matching the `std::string`-constructible overload), but the `from_json` overload for
|
||||
fixed-size arrays expects a JSON *array* and iterates it element-wise, which fails with a `type_error` when
|
||||
given a string. Use `std::string`, `std::array<char, N>`, or a manually written `to_json`/`from_json` pair
|
||||
for such members instead.
|
||||
|
||||
!!! note "Macros and `nlohmann::ordered_json`"
|
||||
|
||||
The `NLOHMANN_DEFINE_TYPE_*`/`NLOHMANN_DEFINE_DERIVED_TYPE_*` macros are generic over any `basic_json`
|
||||
specialization, including `nlohmann::ordered_json`. Simply use `ordered_json` as the target type and members
|
||||
are serialized in declaration order -- no separate macro or extra code is needed.
|
||||
|
||||
```cpp
|
||||
namespace ns {
|
||||
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(person, name, address, age)
|
||||
}
|
||||
|
||||
ns::person p{"Ned Flanders", "744 Evergreen Terrace", 60};
|
||||
nlohmann::ordered_json j = p; // keys appear in declaration order: name, address, age
|
||||
```
|
||||
|
||||
!!! note "No macro for non-default-constructible types"
|
||||
|
||||
There is currently no `NLOHMANN_DEFINE_TYPE_*`-style macro for types that are not
|
||||
[DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). This is not an
|
||||
intentional omission of documentation -- no such macro exists yet; see
|
||||
[How can I use `get()` for non-default constructible/non-copyable types?](#how-can-i-use-get-for-non-default-constructiblenon-copyable-types)
|
||||
for the manual pattern to use instead.
|
||||
|
||||
## How do I convert third-party types?
|
||||
|
||||
This requires a bit more advanced technique. But first, let us see how this conversion mechanism works:
|
||||
@@ -313,49 +270,6 @@ namespace nlohmann {
|
||||
}
|
||||
```
|
||||
|
||||
## Why can't I convert to/from `std::any`?
|
||||
|
||||
`std::any` is intentionally excluded from `get<T>()`/generic conversion support, so `get<std::any>()` and
|
||||
containers like `std::map<std::string, std::any>` fail to compile by design -- there is no way to know, from a
|
||||
`json` value alone, which concrete type to store inside the `std::any`. To work with heterogeneous JSON values,
|
||||
dispatch on the value's type manually and construct the `std::any` (or extract from it) yourself:
|
||||
|
||||
```cpp
|
||||
std::any value_to_any(const json& j) {
|
||||
if (j.is_boolean()) { return j.get<bool>(); }
|
||||
if (j.is_number_integer()) { return j.get<int>(); }
|
||||
if (j.is_number_float()) { return j.get<double>(); }
|
||||
if (j.is_string()) { return j.get<std::string>(); }
|
||||
// ... handle other types (arrays, objects) as needed for your use case
|
||||
return {};
|
||||
}
|
||||
|
||||
json any_to_json(const std::any& a) {
|
||||
if (a.type() == typeid(bool)) { return std::any_cast<bool>(a); }
|
||||
if (a.type() == typeid(int)) { return std::any_cast<int>(a); }
|
||||
if (a.type() == typeid(double)) { return std::any_cast<double>(a); }
|
||||
if (a.type() == typeid(std::string)) { return std::any_cast<std::string>(a); }
|
||||
return nullptr;
|
||||
}
|
||||
```
|
||||
|
||||
## Why does serializing a `std::map`/`std::unordered_map` with non-string keys produce an array?
|
||||
|
||||
A `std::map`/`std::unordered_map` whose key type is not string-like (e.g., `std::map<int, std::string>`) is
|
||||
serialized as a JSON *array* of 2-element `[key, value]` arrays, not as a JSON object -- JSON object keys must be
|
||||
strings, so the library cannot represent an integer-keyed map as an object.
|
||||
|
||||
```cpp
|
||||
std::map<int, std::string> m{{1, "one"}, {2, "two"}};
|
||||
json j = m;
|
||||
// j is [[1,"one"],[2,"two"]], not {"1":"one","2":"two"}
|
||||
```
|
||||
|
||||
## Why does `std::wstring` convert or dump incorrectly?
|
||||
|
||||
The library assumes UTF-8 encoding internally, so `std::wstring` is not supported out of the box -- see the FAQ
|
||||
entry on [wide string handling](../home/faq.md#wide-string-handling) for why, and for a UTF-8 conversion recipe.
|
||||
|
||||
## Can I write my own serializer? (Advanced use)
|
||||
|
||||
Yes. You might want to take a look at [`unit-udt.cpp`](https://github.com/nlohmann/json/blob/develop/tests/src/unit-udt.cpp) in the test suite, to see a few examples.
|
||||
|
||||
@@ -66,15 +66,7 @@ see "binary" cells in the table above.
|
||||
|
||||
!!! info "NaN/infinity handling"
|
||||
|
||||
`NaN`, `Infinity`, and `-Infinity` are serialized as a CBOR half-precision float (type 0xF9, 3 bytes total):
|
||||
`NaN` as `0xF9 0x7E 0x00`, `Infinity` as `0xF9 0x7C 0x00`, and `-Infinity` as `0xF9 0xFC 0x00`. This behavior
|
||||
differs from the normal JSON serialization which serializes NaN or Infinity to `null`.
|
||||
|
||||
!!! note
|
||||
|
||||
Prior to version 3.13.0, NaN and Infinity were instead serialized as a CBOR double-precision float (type 0xFB,
|
||||
9 bytes total), because the check used to select a smaller encoding compared magnitudes with NaN, which is
|
||||
always `false` and caused the intended half-precision path to be skipped.
|
||||
If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the normal JSON serialization which serializes NaN or Infinity to `null`.
|
||||
|
||||
!!! info "Unused CBOR types"
|
||||
|
||||
@@ -168,13 +160,6 @@ The library maps CBOR types to JSON value types as follows:
|
||||
- simple values (0xE0..0xF3, 0xF8)
|
||||
- undefined (0xF7)
|
||||
|
||||
!!! warning "Negative integer overflow"
|
||||
|
||||
CBOR negative integers (major type 1) are decoded as `-1 - n`. If the encoded magnitude `n` is too large for the
|
||||
result to fit into `number_integer_t` (`std::int64_t` by default), parsing fails with a
|
||||
[`parse_error.112`](../../home/exceptions.md#jsonexceptionparse_error112) exception rather than overflowing
|
||||
silently.
|
||||
|
||||
!!! warning "Object keys"
|
||||
|
||||
CBOR allows map keys of any type, whereas JSON only allows strings as keys in object values. Therefore, CBOR maps with keys other than UTF-8 strings are rejected.
|
||||
|
||||
@@ -67,15 +67,8 @@ specification:
|
||||
|
||||
!!! info "NaN/infinity handling"
|
||||
|
||||
`NaN`, `Infinity`, and `-Infinity` are serialized as a MessagePack float 32 (type 0xCA, 5 bytes total),
|
||||
regardless of magnitude, in contrast to the [dump](../../api/basic_json/dump.md) function which serializes NaN
|
||||
or Infinity to `null`.
|
||||
|
||||
!!! note
|
||||
|
||||
Prior to version 3.13.0, NaN and Infinity were instead serialized as a MessagePack float 64 (type 0xCB, 9 bytes
|
||||
total), because the check used to select the smaller float 32 encoding compared magnitudes with NaN, which is
|
||||
always `false` and caused the float 32 path to be skipped.
|
||||
If NaN or Infinity are stored inside a JSON number, they are serialized properly in contrast to the
|
||||
[dump](../../api/basic_json/dump.md) function which serializes NaN or Infinity to `null`.
|
||||
|
||||
??? example
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ This library does not support comments *by default*. It does so for three reason
|
||||
|
||||
3. It is dangerous for interoperability if some libraries add comment support while others do not. 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 parameter `ignore_comments` to `#!cpp true` in the [`parse`](../api/basic_json/parse.md) function to ignore `//` or `/* */` comments. Comments will then be treated as whitespace. Combined with `ignore_trailing_commas` (also a `parse` parameter), this covers what is commonly referred to as **JSONC** (JSON with Comments, as used e.g. by Visual Studio Code's `.jsonc` files) -- comments and trailing commas, nothing more. This is a different, smaller extension than [JSON5](https://json5.org), which additionally allows unquoted keys, single-quoted strings, and other syntax changes that this library does not support.
|
||||
However, you can set parameter `ignore_comments` to `#!cpp true` in the [`parse`](../api/basic_json/parse.md) function to ignore `//` or `/* */` comments. Comments will then be treated as whitespace.
|
||||
|
||||
For more information, see [JSON With Commas and Comments (JWCC)](https://nigeltao.github.io/blog/2021/json-with-commas-comments.html).
|
||||
|
||||
|
||||
@@ -66,67 +66,6 @@ which forces the explicit `get` form and can catch unintended conversions at com
|
||||
floating-point value as an integer truncates it, and narrowing conversions may overflow. See
|
||||
[number conversion](types/number_handling.md#number-conversion) for details and how to guard against it.
|
||||
|
||||
!!! warning "std::optional direct construction from JSON null throws"
|
||||
|
||||
Constructing or assigning `std::optional<T>` directly from a JSON value does not correctly produce
|
||||
`std::nullopt` for a JSON `null`:
|
||||
|
||||
```cpp
|
||||
json j_null;
|
||||
std::optional<std::string> opt = j_null; // ❌ throws type_error 302
|
||||
```
|
||||
|
||||
This is due to C++ language rules: `std::optional<T>` has its own converting constructor that is chosen over
|
||||
`basic_json::operator T()` when both are viable. Use `get<std::optional<T>>()` or `get_to()` instead:
|
||||
|
||||
```cpp
|
||||
auto opt = j_null.get<std::optional<std::string>>(); // ✅ std::nullopt
|
||||
j_null.get_to(opt); // ✅ std::nullopt
|
||||
```
|
||||
|
||||
!!! warning "`static_cast` and `get<std::optional<T>>()` are not guaranteed equivalent"
|
||||
|
||||
`operator ValueType()` (used by `static_cast` and implicit conversions) intentionally excludes
|
||||
`std::optional<T>` from delegating to `get<T>()`, to avoid a constructor ambiguity with
|
||||
`std::optional<T>`'s own converting constructor from `basic_json`. As a result,
|
||||
`static_cast<std::optional<T>>(json_value)` goes through `std::optional<T>`'s own converting
|
||||
constructor rather than through `get<std::optional<T>>()`, which can behave differently -- for example,
|
||||
with a custom `adl_serializer<std::optional<T>>` specialization. Prefer `get<std::optional<T>>()`/`get_to()`
|
||||
over `static_cast` for optional types.
|
||||
|
||||
!!! warning "Converting to a fixed-size `std::array` does not check length"
|
||||
|
||||
Converting a JSON array to `#!cpp std::array<T, N>` does not check that the JSON array's size matches `N`:
|
||||
if the JSON array is longer, the extra elements are silently dropped; if it is shorter, the remaining
|
||||
`std::array` elements are left default-constructed. No exception is thrown in either case.
|
||||
|
||||
```cpp
|
||||
json j = {1, 2, 3, 4, 5};
|
||||
auto a = j.get<std::array<int, 3>>(); // {1, 2, 3} -- elements 4 and 5 silently dropped
|
||||
```
|
||||
|
||||
## Omitting a field when serializing `std::optional`
|
||||
|
||||
By default, `to_json` for `std::optional<T>` writes either the value or `#!json null` -- there is no built-in way
|
||||
to make a field disappear from the serialized object entirely when the `std::optional` is `std::nullopt`. Because
|
||||
a specialization of `adl_serializer<std::optional<T>>` only controls how the *value* is converted (it cannot
|
||||
prevent the containing object's `to_json` from inserting the key in the first place), omission has to be
|
||||
implemented in the *containing* type's `to_json`:
|
||||
|
||||
```cpp
|
||||
struct person {
|
||||
std::string name;
|
||||
std::optional<int> age;
|
||||
};
|
||||
|
||||
void to_json(json& j, const person& p) {
|
||||
j = json{{"name", p.name}};
|
||||
if (p.age) {
|
||||
j["age"] = *p.age; // key is only inserted when the optional has a value
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Putting values in
|
||||
|
||||
The reverse direction works the same way: assigning or constructing a `json` from a C++ value converts it to JSON.
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
|
||||
In many situations, such as configuration files, missing values are not exceptional, but may be treated as if a default
|
||||
value was present. For this case, use [`value(key, default_value)`](../../api/basic_json/value.md) which takes the key
|
||||
you want to access and a default value in case there is no value stored with that key. This is equivalent to Python's
|
||||
`dict.get(key, default)`.
|
||||
you want to access and a default value in case there is no value stored with that key.
|
||||
|
||||
## Example
|
||||
|
||||
|
||||
@@ -102,20 +102,6 @@ that the passed index is the new maximal index. Intermediate values are filled w
|
||||
`operator[]` can only be used with objects (with a string argument) or with arrays (with a numeric argument). For
|
||||
other types, a [`basic_json::type_error`](../../home/exceptions.md#jsonexceptiontype_error305) is thrown.
|
||||
|
||||
## Performance: reserving array capacity
|
||||
|
||||
There is no public `reserve(count)` member on `basic_json` for pre-allocating array capacity. If you are building
|
||||
a large array incrementally (e.g., via repeated `push_back()`) and know its final size ahead of time, you can
|
||||
reserve capacity via `get_ref()` to access the underlying `array_t` directly:
|
||||
|
||||
```cpp
|
||||
json j = json::array();
|
||||
j.get_ref<json::array_t&>().reserve(1000);
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
j.push_back(i);
|
||||
}
|
||||
```
|
||||
|
||||
## Summary
|
||||
|
||||
| scenario | non-const value | const value |
|
||||
|
||||
@@ -77,11 +77,6 @@ auto val2 = j.at(json::json_pointer("/nested/three/1")); // false
|
||||
auto val3 = j.value(json::json_pointer("/nested/four"), 0); // 0
|
||||
```
|
||||
|
||||
!!! note "Creating intermediate levels that don't exist"
|
||||
|
||||
See the [`operator[]` notes](../api/basic_json/operator%5B%5D.md#return-value) for how array vs. object is
|
||||
decided when a pointer creates intermediate levels that don't exist yet.
|
||||
|
||||
## Flatten / unflatten
|
||||
|
||||
The library implements a function [`flatten`](../api/basic_json/flatten.md) to convert any JSON document into a JSON
|
||||
|
||||
@@ -27,7 +27,6 @@ json data = json::parse(f);
|
||||
It should be noted that as modules do not export macros, the `nlohmann.json` module will not export any macros.
|
||||
|
||||
## Exported symbols
|
||||
|
||||
Only the following symbols are exported from `nlohmann.json`:
|
||||
|
||||
- `nlohmann::adl_serializer`
|
||||
@@ -39,21 +38,3 @@ Only the following symbols are exported from `nlohmann.json`:
|
||||
- `nlohmann::to_string`
|
||||
- `nlohmann::literals::json_literals::operator""_json`
|
||||
- `nlohmann::literals::json_literals::operator""_json_pointer`
|
||||
|
||||
Additionally, the following `nlohmann::detail` symbols are exported, solely to work around an MSVC compilation issue
|
||||
([#3970](https://github.com/nlohmann/json/issues/3970)). They are implementation details, not part of the public API,
|
||||
and should not be used directly:
|
||||
|
||||
- `nlohmann::detail::json_sax_dom_callback_parser`
|
||||
- `nlohmann::detail::unknown_size`
|
||||
|
||||
## Known issues
|
||||
|
||||
C++20 modules support is exercised in CI against current GCC and Clang on Ubuntu, and the default MSVC toolset on Windows Server 2022 — there is no documented minimum compiler version, unlike feature-test-macro-gated features such as [`JSON_HAS_RANGES`](../api/macros/json_has_ranges.md).
|
||||
|
||||
!!! info "Known compiler issues"
|
||||
|
||||
- **GCC** may emit "redefinition" errors when `#include <nlohmann/json.hpp>` appears in a module preamble together with other imports. This is an upstream GCC bug, not yet resolved as of GCC 16. Workarounds: include `nlohmann/json.hpp` before other `#include`s, use `import nlohmann.json;` instead, or upgrade GCC. ([issue #5103](https://github.com/nlohmann/json/issues/5103))
|
||||
- **MSVC** could fail with `C2039: 'json_sax_dom_callback_parser' is not a member of ... detail`; fixed by exporting the required internal symbols from `json.cppm` (see [Exported symbols](#exported-symbols) above). ([issue #3970](https://github.com/nlohmann/json/issues/3970))
|
||||
|
||||
If you hit a different module-related build failure, search [existing issues](https://github.com/nlohmann/json/issues?q=is%3Aissue+modules) before filing a new one.
|
||||
|
||||
@@ -47,6 +47,3 @@ JSON Lines input with more than one value is treated as invalid JSON by the [`pa
|
||||
```
|
||||
|
||||
with a JSON Lines input does not work, because the parser will try to parse one value after the last one.
|
||||
|
||||
This is different from parsing a stream of *concatenated* (non-newline-delimited) JSON values, for which
|
||||
`operator>>` does work -- see its [notes](../../api/operator_gtgt.md#notes) for details.
|
||||
|
||||
@@ -58,14 +58,6 @@ table describes the values of the parameters `depth`, `event`, and `parsed`.
|
||||
| `array_end` | 1 | `#!json [52.519444,13.406667]` |
|
||||
| `object_end` | 0 | `#!json {"location":[52.519444,13.406667],"name":"Berlin"}` |
|
||||
|
||||
!!! note "No built-in nesting depth limit"
|
||||
|
||||
The library has no built-in limit on recursion/nesting depth while parsing. A parser callback can only
|
||||
*discard* content it has already parsed (by returning `#!c false`); it cannot make parsing fail once a
|
||||
nesting limit is exceeded partway through reading a deeply nested value. If you need to reject over-deep
|
||||
untrusted input outright, track `depth` in a callback and `throw` from it once your limit is exceeded (a
|
||||
thrown exception propagates out of `parse()` as usual).
|
||||
|
||||
## Return value
|
||||
|
||||
Discarding a value (i.e., returning `#!c false`) has different effects depending on the context in which the function
|
||||
@@ -89,82 +81,3 @@ was called:
|
||||
```json
|
||||
--8<-- "examples/parse__string__parser_callback_t.output"
|
||||
```
|
||||
|
||||
## Recipe: rejecting duplicate object keys
|
||||
|
||||
The JSON specification leaves the handling of objects with repeated keys up to the implementation. As described in
|
||||
[`object_t`](../../api/basic_json/object_t.md#behavior), it is unspecified which value for a repeated key ends up in
|
||||
the resulting `#!c json` value -- once parsing has produced that value, the duplicate is already gone, because object
|
||||
storage maps each key to a single value. If duplicate keys should instead be treated as an error, a parser callback
|
||||
can detect them while the object is still being read, before that ambiguity ever applies.
|
||||
|
||||
??? example
|
||||
|
||||
```cpp
|
||||
--8<-- "examples/reject_duplicate_keys.cpp"
|
||||
```
|
||||
|
||||
Output:
|
||||
|
||||
```json
|
||||
--8<-- "examples/reject_duplicate_keys.output"
|
||||
```
|
||||
|
||||
This approach has two limitations:
|
||||
|
||||
- The depth-indexed bookkeeping must account for the fact that `object_start` reports the depth of the *parent* of
|
||||
the object, while the `key` events inside that object are reported one depth deeper (see the event table above);
|
||||
it is easy to get this off by one for nested objects.
|
||||
- The thrown exception cannot carry a `parse_error`-style byte offset, because position tracking only exists inside
|
||||
the parser and lexer, not at the callback layer.
|
||||
|
||||
For strict validation with precise error positions, implementing a [SAX interface](sax_interface.md) instead gives
|
||||
access to the parser's position information directly.
|
||||
|
||||
## Recipe: streaming a large homogeneous array
|
||||
|
||||
A common use case is a huge top-level array of many similarly-shaped objects, too large to hold entirely in
|
||||
memory as a `#!c json` value. A parser callback can hand off each completed element to a user function and then
|
||||
discard it, so memory usage stays bounded by a single element (plus the not-yet-parsed tail of the input) rather
|
||||
than the whole document. Since the top-level array's `array_start`/`array_end` are reported at `depth == 0` (its
|
||||
parent is the document root), the object elements it contains are reported at `depth == 1`:
|
||||
|
||||
??? example
|
||||
|
||||
```cpp
|
||||
std::ifstream input("large_array.json");
|
||||
|
||||
auto callback = [](int depth, json::parse_event_t event, json& parsed) -> bool {
|
||||
if (depth == 1 && event == json::parse_event_t::object_end) {
|
||||
handle_element(parsed); // process the element, e.g. write it elsewhere
|
||||
return false; // discard it -- frees its memory before the next one is parsed
|
||||
}
|
||||
return true; // keep everything else, including the (by then empty) top-level array
|
||||
};
|
||||
|
||||
json::parse(input, callback);
|
||||
```
|
||||
|
||||
If the array's elements are scalars or nested arrays instead of objects, check for `parse_event_t::value` or
|
||||
`parse_event_t::array_end` at `depth == 1` instead. The same approach works for a top-level *object* of many
|
||||
homogeneous values by checking `object_end`/`value` events at `depth == 1` there too.
|
||||
|
||||
## Recipe: max nesting depth via a callback
|
||||
|
||||
Since there is no built-in nesting-depth limit (see the note above), a callback can enforce one manually by
|
||||
tracking the maximum `depth` seen and throwing once it is exceeded:
|
||||
|
||||
??? example
|
||||
|
||||
```cpp
|
||||
constexpr int max_depth = 32;
|
||||
|
||||
auto callback = [](int depth, json::parse_event_t /*event*/, json& /*parsed*/) -> bool {
|
||||
if (depth > max_depth) {
|
||||
throw std::runtime_error("maximum nesting depth exceeded");
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
json::parse(input, callback);
|
||||
```
|
||||
|
||||
@@ -131,7 +131,7 @@ std::map<
|
||||
The choice of `object_t` influences the behavior of the JSON class. With the default type, objects have the following behavior:
|
||||
|
||||
- When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings.
|
||||
- When the names within an object are not unique, it is unspecified which one of the values for a given key will be chosen. For instance, `#!json {"key": 2, "key": 1}` could be equal to either `#!json {"key": 1}` or `#!json {"key": 2}`. To reject duplicate keys instead of silently resolving them one way or another, see [this parsing recipe](../parsing/parser_callbacks.md#recipe-rejecting-duplicate-object-keys).
|
||||
- When the names within an object are not unique, it is unspecified which one of the values for a given key will be chosen. For instance, `#!json {"key": 2, "key": 1}` could be equal to either `#!json {"key": 1}` or `#!json {"key": 2}`.
|
||||
- Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see `dump`) in this order. For instance, both `#!json {"b": 1, "a": 2}` and `#!json {"a": 2, "b": 1}` will be stored and serialized as `#!json {"a": 2, "b": 1}`.
|
||||
- When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, `#!json {"b": 1, "a": 2}` and `#!json {"a": 2, "b": 1}` will be treated as equal.
|
||||
|
||||
@@ -151,18 +151,6 @@ In this class, the object's limit of nesting is not explicitly constrained. Howe
|
||||
|
||||
Objects are stored as pointers in a `basic_json` type. That is, for any access to object values, a pointer of type `object_t*` must be dereferenced.
|
||||
|
||||
### Converting maps with non-string keys
|
||||
|
||||
A `std::map`/`std::unordered_map` whose key type is not string-like (e.g., `std::map<int, std::string>`) is
|
||||
converted to a JSON *array* of 2-element `[key, value]` arrays rather than a JSON object, because JSON object
|
||||
keys must be strings:
|
||||
|
||||
```cpp
|
||||
std::map<int, std::string> m{{1, "one"}, {2, "two"}};
|
||||
json j = m;
|
||||
// j is [[1,"one"],[2,"two"]], not {"1":"one","2":"two"}
|
||||
```
|
||||
|
||||
|
||||
## Arrays
|
||||
|
||||
|
||||
@@ -63,10 +63,6 @@ In the default [`json`](../../api/json.md) type, numbers are stored as `#!c std:
|
||||
number without loss of precision. If this is impossible (e.g., if the number is too large), the number is stored as
|
||||
`#!c double`.
|
||||
|
||||
Positive integers are stored as `#!c std::uint64_t`, while negative integers are stored as `#!c std::int64_t`. This
|
||||
distinction is determined at parse time: if the JSON number has a leading minus sign, it uses signed integer storage;
|
||||
otherwise, it uses unsigned integer storage.
|
||||
|
||||
!!! info "Notes"
|
||||
|
||||
- Numbers with a decimal digit or scientific notation are always stored as `#!c double`.
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
# Debugging
|
||||
|
||||
This page collects the library's built-in debugger integrations and other debugging-related features. They are
|
||||
not linked from a single place elsewhere in the docs, so are collected here.
|
||||
|
||||
## Visual Studio (natvis)
|
||||
|
||||
The repository ships [`nlohmann_json.natvis`](https://github.com/nlohmann/json/blob/develop/nlohmann_json.natvis)
|
||||
at its root, a [Natvis](https://learn.microsoft.com/en-us/visualstudio/debugger/create-custom-views-of-native-objects)
|
||||
file that gives `json`/`ordered_json` values a friendly, key/value debugger view instead of showing raw internal
|
||||
fields, when debugging with the MSVC debug engine (`cppvsdbg`) in Visual Studio or VS Code.
|
||||
|
||||
Debug engines that wrap LLDB instead of the MSVC debug engine (for example, `codelldb` in VS Code) only have
|
||||
partial/experimental Natvis support, and commonly fall back to showing raw internal fields even with the
|
||||
`.natvis` file present. Switching to `cppvsdbg` where available, or checking your debug extension's own Natvis
|
||||
support/version, are the next things to try if this happens. There is currently no bundled LLDB-native
|
||||
pretty-printer script in this repository.
|
||||
|
||||
## GDB
|
||||
|
||||
The repository ships a [GDB Python pretty printer](https://github.com/nlohmann/json/tree/develop/tools/gdb_pretty_printer)
|
||||
under `tools/gdb_pretty_printer`, with its own usage instructions in that directory's `README.md`.
|
||||
|
||||
## Extended exception diagnostics
|
||||
|
||||
Defining [`JSON_DIAGNOSTICS`](../api/macros/json_diagnostics.md) before including the library augments
|
||||
`type_error`/`out_of_range`-style exceptions with a JSON Pointer to the offending value, which can help pinpoint
|
||||
where in a large document a runtime error occurred. This only applies to exceptions thrown *after* a value
|
||||
exists (e.g. during element access); parse errors, which happen before any value exists to point at, are not
|
||||
covered by this mechanism -- see [Parsing and exceptions](../features/parsing/parse_exceptions.md) for how parse
|
||||
errors report their own location instead.
|
||||
@@ -326,9 +326,6 @@ An unexpected byte was read in a [binary format](../features/binary_formats/inde
|
||||
```
|
||||
[json.exception.parse_error.112] parse error at byte 15: syntax error while parsing BSON binary: byte array length cannot be negative, is -1
|
||||
```
|
||||
```
|
||||
[json.exception.parse_error.112] parse error at byte 9: syntax error while parsing CBOR value: negative integer overflow
|
||||
```
|
||||
|
||||
### json.exception.parse_error.113
|
||||
|
||||
@@ -896,7 +893,7 @@ A JSON Patch `add` operation cannot be applied because the target location's par
|
||||
|
||||
!!! note
|
||||
|
||||
This exception was added in version 3.13.0. Before that, this situation hit an internal assertion (aborting the program in debug builds) or was silently ignored when assertions were disabled.
|
||||
This exception was added in version 3.12.x. Before that, this situation hit an internal assertion (aborting the program in debug builds) or was silently ignored when assertions were disabled.
|
||||
|
||||
## Further exceptions
|
||||
|
||||
|
||||
@@ -129,29 +129,6 @@ As described [above](#parse-errors-reading-non-ascii-characters), the library as
|
||||
}
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Thread safety
|
||||
|
||||
!!! question
|
||||
|
||||
Is `basic_json` thread-safe?
|
||||
|
||||
No. `basic_json` provides no built-in synchronization, the same as `std::map` or `std::vector`. Concurrent reads of
|
||||
the same value from multiple threads are safe, as are concurrent (non-overlapping) accesses to independent `json`
|
||||
objects. However, any concurrent write to a `json` object -- or a concurrent read while another thread writes to the
|
||||
same object -- is a data race and requires external synchronization (e.g., a `std::mutex`) by the caller.
|
||||
|
||||
### Schema validation
|
||||
|
||||
!!! question
|
||||
|
||||
Does this library support JSON Schema validation?
|
||||
|
||||
Not directly, but the companion project [json-schema-validator](https://github.com/pboettch/json-schema-validator)
|
||||
builds JSON Schema (draft 4, 6, 7, and 2019-09) validation on top of this library and is a common recommendation
|
||||
for this use case.
|
||||
|
||||
## Exceptions
|
||||
|
||||
### Parsing without exceptions
|
||||
@@ -201,7 +178,7 @@ See [this section](../features/types/number_handling.md#number-serialization) on
|
||||
- Can I use `std::format("{}", j)` on a JSON value?
|
||||
- Can I use `fmt::format("{}", j)` or `fmt::print("{}", j)` (the [{fmt}](https://github.com/fmtlib/fmt) library) on a JSON value?
|
||||
|
||||
`std::format` works out of the box since version 3.13.0, as long as the standard library provides
|
||||
`std::format` works out of the box since version 3.12.x, as long as the standard library provides
|
||||
`<format>` (see [`JSON_HAS_STD_FORMAT`](../api/macros/json_has_std_format.md)); see
|
||||
[`std::formatter<basic_json>`](../api/basic_json/std_formatter.md) for details, including the `#!cpp "{:#}"`
|
||||
pretty-print spec, indent widths (`#!cpp "{:2}"`), and custom indent characters (`#!cpp "{:.>#}"`).
|
||||
|
||||
@@ -181,15 +181,3 @@ Execute the test suite with [Valgrind](https://valgrind.org). This option is `OF
|
||||
|
||||
Build the experimental [C++ module](../features/modules.md) `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:
|
||||
|
||||
```cmake
|
||||
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)
|
||||
```
|
||||
|
||||
@@ -930,15 +930,6 @@ If you are using [CocoaPods](https://cocoapods.org), you can use the library by
|
||||
to your podfile (see [an example](https://bitbucket.org/benman/nlohmann_json-cocoapod/src/master/)). Please file issues
|
||||
[here](https://bitbucket.org/benman/nlohmann_json-cocoapod/issues?status=new&status=open).
|
||||
|
||||
## ESP-IDF and PlatformIO
|
||||
|
||||
There is no official package published to the [ESP-IDF Component Registry](https://components.espressif.com) or the
|
||||
[PlatformIO Registry](https://registry.platformio.org). A community-maintained fork,
|
||||
[Johboh/nlohmann-json](https://github.com/Johboh/nlohmann-json), publishes this library to both registries on each
|
||||
new release and can be used as an unofficial component/package for ESP-IDF and PlatformIO projects. As the library
|
||||
is header-only, it can otherwise be used directly by adding its `include/` directory to your component's/project's
|
||||
include paths, like any other integration method described on this page.
|
||||
|
||||

|
||||
|
||||
!!! warning
|
||||
|
||||
@@ -56,7 +56,6 @@ nav:
|
||||
- home/architecture.md
|
||||
- home/customers.md
|
||||
- home/sponsors.md
|
||||
- home/debugging.md
|
||||
- Features:
|
||||
- features/index.md
|
||||
- features/arbitrary_types.md
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
#include <cstdint> // uint8_t
|
||||
#include <cstddef> // size_t
|
||||
#include <functional> // hash
|
||||
#include <limits> // numeric_limits
|
||||
#include <cmath> // isfinite
|
||||
|
||||
#include <nlohmann/detail/abi_macros.hpp>
|
||||
#include <nlohmann/detail/value_t.hpp>
|
||||
@@ -26,12 +28,73 @@ inline std::size_t combine(std::size_t seed, std::size_t h) noexcept
|
||||
return seed;
|
||||
}
|
||||
|
||||
// Check if a number_integer_t value is exactly representable as number_float_t
|
||||
// Returns true if static_cast<number_integer_t>(static_cast<number_float_t>(val)) == val
|
||||
template<typename BasicJsonType>
|
||||
inline bool is_exactly_representable_as_float(typename BasicJsonType::number_integer_t val) noexcept
|
||||
{
|
||||
using number_integer_t = typename BasicJsonType::number_integer_t;
|
||||
using number_float_t = typename BasicJsonType::number_float_t;
|
||||
|
||||
// If the float type's mantissa covers the integer type's entire range, all values round-trip
|
||||
constexpr int float_digits = std::numeric_limits<number_float_t>::digits;
|
||||
constexpr int int_digits = std::numeric_limits<number_integer_t>::digits;
|
||||
|
||||
#ifdef JSON_HEDLEY_MSVC_VERSION
|
||||
#pragma warning(push )
|
||||
#pragma warning(disable : 4127) // ignore warning to replace if with if constexpr
|
||||
#endif
|
||||
if (float_digits >= int_digits)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
#ifdef JSON_HEDLEY_MSVC_VERSION
|
||||
#pragma warning( pop )
|
||||
#endif
|
||||
|
||||
// For values outside float's exact range, they don't round-trip
|
||||
// The safe way to check: compute the max magnitude that round-trips
|
||||
// Using unsigned arithmetic to avoid UB with negating INT_MIN
|
||||
|
||||
// Max magnitude representable exactly: 2^(digits-1) - 1 for signed, 2^digits - 1 for unsigned range
|
||||
// But we're checking a signed value, so use 2^digits as the threshold
|
||||
constexpr auto max_exact = static_cast<number_integer_t>(1) << (float_digits - 1);
|
||||
|
||||
// Check absolute value against this threshold
|
||||
if (val >= 0)
|
||||
{
|
||||
if (val >= max_exact)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// For negative values, check via unsigned wrapping arithmetic
|
||||
// -val in unsigned domain; if it wraps, the value is too negative
|
||||
auto unsigned_abs = static_cast<typename BasicJsonType::number_unsigned_t>(-val);
|
||||
if (unsigned_abs >= static_cast<typename BasicJsonType::number_unsigned_t>(max_exact))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// For values within the exact range, verify the round-trip
|
||||
const auto f = static_cast<number_float_t>(val);
|
||||
return std::isfinite(f) && static_cast<number_integer_t>(f) == val;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief hash a JSON value
|
||||
|
||||
The hash function tries to rely on std::hash where possible. Furthermore, the
|
||||
type of the JSON value is taken into account to have different hash values for
|
||||
null, 0, 0U, and false, etc.
|
||||
most types. However, numeric types (number_integer, number_unsigned, number_float)
|
||||
are hashed to satisfy the std::hash contract: if two json values compare equal,
|
||||
they must have equal hash values. This means json(42), json(42u), and json(42.0)
|
||||
all hash to the same value (since they compare equal). For large integer values
|
||||
outside the exact representable range of the float type, integer values are hashed
|
||||
in their own domain to avoid precision loss.
|
||||
|
||||
@tparam BasicJsonType basic_json specialization
|
||||
@param j JSON value to hash
|
||||
@@ -90,14 +153,36 @@ std::size_t hash(const BasicJsonType& j)
|
||||
|
||||
case BasicJsonType::value_t::number_integer:
|
||||
{
|
||||
const auto h = std::hash<number_integer_t> {}(j.template get<number_integer_t>());
|
||||
return combine(type, h);
|
||||
const auto v = j.template get<number_integer_t>();
|
||||
// Use a shared numeric type tag so all numeric types that are equal hash the same
|
||||
const auto numeric_type = static_cast<std::size_t>(BasicJsonType::value_t::number_float);
|
||||
|
||||
if (is_exactly_representable_as_float<BasicJsonType>(v))
|
||||
{
|
||||
const auto h = std::hash<number_float_t> {}(static_cast<number_float_t>(v));
|
||||
return combine(numeric_type, h);
|
||||
}
|
||||
|
||||
const auto h = std::hash<number_integer_t> {}(v);
|
||||
return combine(numeric_type, h);
|
||||
}
|
||||
|
||||
case BasicJsonType::value_t::number_unsigned:
|
||||
{
|
||||
const auto h = std::hash<number_unsigned_t> {}(j.template get<number_unsigned_t>());
|
||||
return combine(type, h);
|
||||
const auto v = j.template get<number_unsigned_t>();
|
||||
// Normalize to signed (matching operator== behavior for U-vs-I comparison)
|
||||
const auto v_as_signed = static_cast<number_integer_t>(v);
|
||||
// Use a shared numeric type tag so all numeric types that are equal hash the same
|
||||
const auto numeric_type = static_cast<std::size_t>(BasicJsonType::value_t::number_float);
|
||||
|
||||
if (is_exactly_representable_as_float<BasicJsonType>(v_as_signed))
|
||||
{
|
||||
const auto h = std::hash<number_float_t> {}(static_cast<number_float_t>(v_as_signed));
|
||||
return combine(numeric_type, h);
|
||||
}
|
||||
|
||||
const auto h = std::hash<number_integer_t> {}(v_as_signed);
|
||||
return combine(numeric_type, h);
|
||||
}
|
||||
|
||||
case BasicJsonType::value_t::number_float:
|
||||
|
||||
@@ -430,7 +430,7 @@ class wide_string_input_adapter
|
||||
|
||||
// parsing binary with wchar doesn't make sense, but since the parsing mode can be runtime, we need something here
|
||||
template<class T>
|
||||
JSON_HEDLEY_NO_RETURN std::size_t get_elements(T* /*dest*/, std::size_t /*count*/ = 1)
|
||||
std::size_t get_elements(T* /*dest*/, std::size_t /*count*/ = 1)
|
||||
{
|
||||
JSON_THROW(parse_error::create(112, 1, "wide string type cannot be interpreted as binary data", nullptr));
|
||||
}
|
||||
|
||||
@@ -146,11 +146,6 @@
|
||||
#define JSON_HAS_RANGES 0
|
||||
#elif defined(_LIBCPP_VERSION) && _LIBCPP_VERSION < 160000
|
||||
#define JSON_HAS_RANGES 0
|
||||
// nvcc CUDA 12.0/12.1 chokes on the enable_borrowed_range variable-template
|
||||
// syntax when compiling as CUDA source; fixed in CUDA 12.2 (issue #3907)
|
||||
#elif defined(__CUDACC__) && defined(__CUDACC_VER_MAJOR__) && __CUDACC_VER_MAJOR__ == 12 \
|
||||
&& defined(__CUDACC_VER_MINOR__) && (__CUDACC_VER_MINOR__ == 0 || __CUDACC_VER_MINOR__ == 1)
|
||||
#define JSON_HAS_RANGES 0
|
||||
#elif defined(__cpp_lib_ranges)
|
||||
#define JSON_HAS_RANGES 1
|
||||
#else
|
||||
|
||||
@@ -3776,6 +3776,17 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
return *this == basic_json(rhs);
|
||||
}
|
||||
|
||||
/// @brief comparison: not equal
|
||||
/// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
|
||||
bool operator!=(const_reference rhs) const noexcept
|
||||
{
|
||||
if (compares_unordered(rhs, true))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return !operator==(rhs);
|
||||
}
|
||||
|
||||
/// @brief comparison: 3-way
|
||||
/// @sa https://json.nlohmann.me/api/basic_json/operator_spaceship/
|
||||
std::partial_ordering operator<=>(const_reference rhs) const noexcept // *NOPAD*
|
||||
@@ -3881,6 +3892,10 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
/// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
|
||||
friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
|
||||
{
|
||||
if (compares_unordered(lhs, rhs, true))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return !(lhs == rhs);
|
||||
}
|
||||
|
||||
|
||||
@@ -2520,11 +2520,6 @@ JSON_HEDLEY_DIAGNOSTIC_POP
|
||||
#define JSON_HAS_RANGES 0
|
||||
#elif defined(_LIBCPP_VERSION) && _LIBCPP_VERSION < 160000
|
||||
#define JSON_HAS_RANGES 0
|
||||
// nvcc CUDA 12.0/12.1 chokes on the enable_borrowed_range variable-template
|
||||
// syntax when compiling as CUDA source; fixed in CUDA 12.2 (issue #3907)
|
||||
#elif defined(__CUDACC__) && defined(__CUDACC_VER_MAJOR__) && __CUDACC_VER_MAJOR__ == 12 \
|
||||
&& defined(__CUDACC_VER_MINOR__) && (__CUDACC_VER_MINOR__ == 0 || __CUDACC_VER_MINOR__ == 1)
|
||||
#define JSON_HAS_RANGES 0
|
||||
#elif defined(__cpp_lib_ranges)
|
||||
#define JSON_HAS_RANGES 1
|
||||
#else
|
||||
@@ -6682,6 +6677,8 @@ NLOHMANN_JSON_NAMESPACE_END
|
||||
#include <cstdint> // uint8_t
|
||||
#include <cstddef> // size_t
|
||||
#include <functional> // hash
|
||||
#include <limits> // numeric_limits
|
||||
#include <cmath> // isfinite
|
||||
|
||||
// #include <nlohmann/detail/abi_macros.hpp>
|
||||
|
||||
@@ -6699,12 +6696,73 @@ inline std::size_t combine(std::size_t seed, std::size_t h) noexcept
|
||||
return seed;
|
||||
}
|
||||
|
||||
// Check if a number_integer_t value is exactly representable as number_float_t
|
||||
// Returns true if static_cast<number_integer_t>(static_cast<number_float_t>(val)) == val
|
||||
template<typename BasicJsonType>
|
||||
inline bool is_exactly_representable_as_float(typename BasicJsonType::number_integer_t val) noexcept
|
||||
{
|
||||
using number_integer_t = typename BasicJsonType::number_integer_t;
|
||||
using number_float_t = typename BasicJsonType::number_float_t;
|
||||
|
||||
// If the float type's mantissa covers the integer type's entire range, all values round-trip
|
||||
constexpr int float_digits = std::numeric_limits<number_float_t>::digits;
|
||||
constexpr int int_digits = std::numeric_limits<number_integer_t>::digits;
|
||||
|
||||
#ifdef JSON_HEDLEY_MSVC_VERSION
|
||||
#pragma warning(push )
|
||||
#pragma warning(disable : 4127) // ignore warning to replace if with if constexpr
|
||||
#endif
|
||||
if (float_digits >= int_digits)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
#ifdef JSON_HEDLEY_MSVC_VERSION
|
||||
#pragma warning( pop )
|
||||
#endif
|
||||
|
||||
// For values outside float's exact range, they don't round-trip
|
||||
// The safe way to check: compute the max magnitude that round-trips
|
||||
// Using unsigned arithmetic to avoid UB with negating INT_MIN
|
||||
|
||||
// Max magnitude representable exactly: 2^(digits-1) - 1 for signed, 2^digits - 1 for unsigned range
|
||||
// But we're checking a signed value, so use 2^digits as the threshold
|
||||
constexpr auto max_exact = static_cast<number_integer_t>(1) << (float_digits - 1);
|
||||
|
||||
// Check absolute value against this threshold
|
||||
if (val >= 0)
|
||||
{
|
||||
if (val >= max_exact)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// For negative values, check via unsigned wrapping arithmetic
|
||||
// -val in unsigned domain; if it wraps, the value is too negative
|
||||
auto unsigned_abs = static_cast<typename BasicJsonType::number_unsigned_t>(-val);
|
||||
if (unsigned_abs >= static_cast<typename BasicJsonType::number_unsigned_t>(max_exact))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// For values within the exact range, verify the round-trip
|
||||
const auto f = static_cast<number_float_t>(val);
|
||||
return std::isfinite(f) && static_cast<number_integer_t>(f) == val;
|
||||
}
|
||||
|
||||
/*!
|
||||
@brief hash a JSON value
|
||||
|
||||
The hash function tries to rely on std::hash where possible. Furthermore, the
|
||||
type of the JSON value is taken into account to have different hash values for
|
||||
null, 0, 0U, and false, etc.
|
||||
most types. However, numeric types (number_integer, number_unsigned, number_float)
|
||||
are hashed to satisfy the std::hash contract: if two json values compare equal,
|
||||
they must have equal hash values. This means json(42), json(42u), and json(42.0)
|
||||
all hash to the same value (since they compare equal). For large integer values
|
||||
outside the exact representable range of the float type, integer values are hashed
|
||||
in their own domain to avoid precision loss.
|
||||
|
||||
@tparam BasicJsonType basic_json specialization
|
||||
@param j JSON value to hash
|
||||
@@ -6763,14 +6821,36 @@ std::size_t hash(const BasicJsonType& j)
|
||||
|
||||
case BasicJsonType::value_t::number_integer:
|
||||
{
|
||||
const auto h = std::hash<number_integer_t> {}(j.template get<number_integer_t>());
|
||||
return combine(type, h);
|
||||
const auto v = j.template get<number_integer_t>();
|
||||
// Use a shared numeric type tag so all numeric types that are equal hash the same
|
||||
const auto numeric_type = static_cast<std::size_t>(BasicJsonType::value_t::number_float);
|
||||
|
||||
if (is_exactly_representable_as_float<BasicJsonType>(v))
|
||||
{
|
||||
const auto h = std::hash<number_float_t> {}(static_cast<number_float_t>(v));
|
||||
return combine(numeric_type, h);
|
||||
}
|
||||
|
||||
const auto h = std::hash<number_integer_t> {}(v);
|
||||
return combine(numeric_type, h);
|
||||
}
|
||||
|
||||
case BasicJsonType::value_t::number_unsigned:
|
||||
{
|
||||
const auto h = std::hash<number_unsigned_t> {}(j.template get<number_unsigned_t>());
|
||||
return combine(type, h);
|
||||
const auto v = j.template get<number_unsigned_t>();
|
||||
// Normalize to signed (matching operator== behavior for U-vs-I comparison)
|
||||
const auto v_as_signed = static_cast<number_integer_t>(v);
|
||||
// Use a shared numeric type tag so all numeric types that are equal hash the same
|
||||
const auto numeric_type = static_cast<std::size_t>(BasicJsonType::value_t::number_float);
|
||||
|
||||
if (is_exactly_representable_as_float<BasicJsonType>(v_as_signed))
|
||||
{
|
||||
const auto h = std::hash<number_float_t> {}(static_cast<number_float_t>(v_as_signed));
|
||||
return combine(numeric_type, h);
|
||||
}
|
||||
|
||||
const auto h = std::hash<number_integer_t> {}(v_as_signed);
|
||||
return combine(numeric_type, h);
|
||||
}
|
||||
|
||||
case BasicJsonType::value_t::number_float:
|
||||
@@ -7267,7 +7347,7 @@ class wide_string_input_adapter
|
||||
|
||||
// parsing binary with wchar doesn't make sense, but since the parsing mode can be runtime, we need something here
|
||||
template<class T>
|
||||
JSON_HEDLEY_NO_RETURN std::size_t get_elements(T* /*dest*/, std::size_t /*count*/ = 1)
|
||||
std::size_t get_elements(T* /*dest*/, std::size_t /*count*/ = 1)
|
||||
{
|
||||
JSON_THROW(parse_error::create(112, 1, "wide string type cannot be interpreted as binary data", nullptr));
|
||||
}
|
||||
@@ -24627,6 +24707,17 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
return *this == basic_json(rhs);
|
||||
}
|
||||
|
||||
/// @brief comparison: not equal
|
||||
/// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
|
||||
bool operator!=(const_reference rhs) const noexcept
|
||||
{
|
||||
if (compares_unordered(rhs, true))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return !operator==(rhs);
|
||||
}
|
||||
|
||||
/// @brief comparison: 3-way
|
||||
/// @sa https://json.nlohmann.me/api/basic_json/operator_spaceship/
|
||||
std::partial_ordering operator<=>(const_reference rhs) const noexcept // *NOPAD*
|
||||
@@ -24732,6 +24823,10 @@ class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-spec
|
||||
/// @sa https://json.nlohmann.me/api/basic_json/operator_ne/
|
||||
friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
|
||||
{
|
||||
if (compares_unordered(lhs, rhs, true))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
return !(lhs == rhs);
|
||||
}
|
||||
|
||||
|
||||
@@ -68,11 +68,7 @@ target_compile_options(test_main PUBLIC
|
||||
# Disable warning C4566: character represented by universal-character-name '\uFF01'
|
||||
# cannot be represented in the current code page (1252)
|
||||
# Disable warning C4996: 'nlohmann::basic_json<...>::operator <<': was declared deprecated
|
||||
# Disable warning C4702: unreachable code; wide_string_input_adapter::get_elements()
|
||||
# is annotated JSON_HEDLEY_NO_RETURN (it always throws), which
|
||||
# makes MSVC flag the code following its call in binary_reader.hpp
|
||||
# as unreachable for that instantiation, in both Debug and Release
|
||||
$<$<CXX_COMPILER_ID:MSVC>:/W4;/wd4566;/wd4996;/wd4702>
|
||||
$<$<CXX_COMPILER_ID:MSVC>:/W4;/wd4566;/wd4996;$<$<CONFIG:Release>:/wd4702>>
|
||||
# https://github.com/nlohmann/json/issues/1114
|
||||
$<$<CXX_COMPILER_ID:MSVC>:/bigobj> $<$<BOOL:${MINGW}>:-Wa,-mbig-obj>
|
||||
|
||||
|
||||
@@ -3,18 +3,7 @@ project(json_cuda LANGUAGES CUDA)
|
||||
|
||||
add_executable(json_cuda json_cuda.cu)
|
||||
target_include_directories(json_cuda PRIVATE ../../include)
|
||||
|
||||
# nvcc added C++20 support in CUDA 12.0 and C++17 in CUDA 11.0; pick the
|
||||
# newest standard the detected compiler actually supports (see #3907)
|
||||
# instead of hard-requiring one standard for every CUDA version.
|
||||
if(CMAKE_CUDA_COMPILER_VERSION VERSION_GREATER_EQUAL 12.0)
|
||||
set(json_cuda_std 20)
|
||||
elseif(CMAKE_CUDA_COMPILER_VERSION VERSION_GREATER_EQUAL 11.0)
|
||||
set(json_cuda_std 17)
|
||||
else()
|
||||
set(json_cuda_std 11)
|
||||
endif()
|
||||
target_compile_features(json_cuda PUBLIC cuda_std_${json_cuda_std})
|
||||
target_compile_features(json_cuda PUBLIC cuda_std_11)
|
||||
set_target_properties(json_cuda PROPERTIES
|
||||
CUDA_EXTENSIONS OFF
|
||||
CUDA_STANDARD_REQUIRED ON
|
||||
|
||||
@@ -16,20 +16,4 @@ int main()
|
||||
// regression for #3013 (ordered_json::reset() compile error with nvcc)
|
||||
nlohmann::ordered_json metadata;
|
||||
metadata.erase("key");
|
||||
|
||||
// exercise comparisons (operator==/operator<=>, gated by
|
||||
// JSON_HAS_THREE_WAY_COMPARISON, independent of JSON_HAS_RANGES) and
|
||||
// range-based iteration (exercises iteration_proxy/ranges machinery
|
||||
// beyond just the enable_borrowed_range specialization) — see #3907
|
||||
nlohmann::json a = {1, 2, 3};
|
||||
nlohmann::json b = {1, 2, 3};
|
||||
static_cast<void>(a == b);
|
||||
#if JSON_HAS_THREE_WAY_COMPARISON
|
||||
static_cast<void>(a <=> b); // *NOPAD*
|
||||
static_cast<void>(a <=> 1); // *NOPAD*
|
||||
#endif
|
||||
for (const auto& element : a)
|
||||
{
|
||||
static_cast<void>(element);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ struct bad_allocator : std::allocator<T>
|
||||
template<class U> bad_allocator(const bad_allocator<U>& /*unused*/) { }
|
||||
|
||||
template<class... Args>
|
||||
[[noreturn]] void construct(T* /*unused*/, Args&& ... /*unused*/) // NOLINT(cppcoreguidelines-missing-std-forward)
|
||||
void construct(T* /*unused*/, Args&& ... /*unused*/) // NOLINT(cppcoreguidelines-missing-std-forward)
|
||||
{
|
||||
throw std::bad_alloc();
|
||||
}
|
||||
|
||||
@@ -369,7 +369,6 @@ TEST_CASE("lexicographical comparison operators")
|
||||
SECTION("comparison: not equal")
|
||||
{
|
||||
// check that two values compare unequal as expected
|
||||
// operator!= now means exactly !(a==b) without special cases for NaN/discarded
|
||||
for (size_t i = 0; i < j_values.size(); ++i)
|
||||
{
|
||||
for (size_t j = 0; j < j_values.size(); ++j)
|
||||
@@ -377,12 +376,25 @@ TEST_CASE("lexicographical comparison operators")
|
||||
CAPTURE(i)
|
||||
CAPTURE(j)
|
||||
|
||||
CHECK((j_values[i] != j_values[j]) == !(j_values[i] == j_values[j]));
|
||||
if (json::compares_unordered(j_values[i], j_values[j], true))
|
||||
{
|
||||
// if two values compare unordered,
|
||||
// check that the boolean comparison result is always false
|
||||
CHECK_FALSE(j_values[i] != j_values[j]);
|
||||
}
|
||||
else
|
||||
{
|
||||
// otherwise, check that they compare according to their definition
|
||||
// as the inverse of equal
|
||||
CHECK((j_values[i] != j_values[j]) == !(j_values[i] == j_values[j]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// compare with null pointer
|
||||
const json j_null;
|
||||
CHECK((j_null != nullptr) == false);
|
||||
CHECK((nullptr != j_null) == false);
|
||||
CHECK((j_null != nullptr) == !(j_null == nullptr));
|
||||
CHECK((nullptr != j_null) == !(nullptr == j_null));
|
||||
}
|
||||
@@ -582,34 +594,3 @@ TEST_CASE("lexicographical comparison operators")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if JSON_HAS_THREE_WAY_COMPARISON
|
||||
// JSON_HAS_CPP_20 (do not remove; see note at top of file)
|
||||
|
||||
TEST_CASE("regression #3868 - heterogeneous comparisons compile under C++20 (P2468R2)")
|
||||
{
|
||||
// Issue #3868: operator!= was preventing compiler from synthesizing reversed
|
||||
// operator== candidates under C++20's P2468R2 rewritten candidate rules.
|
||||
// Verify that heterogeneous comparisons now work.
|
||||
|
||||
SECTION("string vs json")
|
||||
{
|
||||
std::string s = "string";
|
||||
json j = "string";
|
||||
CHECK(s == j);
|
||||
CHECK(j == s);
|
||||
CHECK_FALSE(s != j);
|
||||
CHECK_FALSE(j != s);
|
||||
}
|
||||
|
||||
SECTION("other heterogeneous types")
|
||||
{
|
||||
int i = 42;
|
||||
json j = 42;
|
||||
CHECK(i == j);
|
||||
CHECK(j == i);
|
||||
CHECK_FALSE(i != j);
|
||||
CHECK_FALSE(j != i);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -278,7 +278,7 @@ TEST_CASE("constructors")
|
||||
const auto t = j.get<std::tuple<int, float, std::string>>();
|
||||
CHECK(std::get<0>(t) == j[0]);
|
||||
CHECK(std::get<1>(t) == j[1]);
|
||||
CHECK(std::get<2>(t) == j[2]);
|
||||
// CHECK(std::get<2>(t) == j[2]); // commented out due to CI issue, see https://github.com/nlohmann/json/pull/3985 and https://github.com/nlohmann/json/issues/4025
|
||||
}
|
||||
|
||||
SECTION("std::tuple tie")
|
||||
|
||||
@@ -1761,27 +1761,16 @@ TEST_CASE("std::filesystem::path")
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !JSON_USE_IMPLICIT_CONVERSIONS
|
||||
TEST_CASE("std::optional")
|
||||
{
|
||||
SECTION("null")
|
||||
{
|
||||
const json j_null;
|
||||
const std::optional<std::string> opt_null;
|
||||
json j_null;
|
||||
std::optional<std::string> opt_null;
|
||||
|
||||
CHECK(json(opt_null) == j_null);
|
||||
CHECK(j_null.get<std::optional<std::string>>() == std::nullopt);
|
||||
|
||||
// Constructing std::optional<T> directly from JSON null throws because
|
||||
// std::optional's own converting constructor is chosen over basic_json's
|
||||
// operator T(). This is a language-level limitation (std::optional<T> is
|
||||
// constructible from T, and T is constructible from basic_json via the
|
||||
// operator); there is no SFINAE path that distinguishes "call from inside
|
||||
// std::optional's constructor" from "direct call". Use get<std::optional<T>>()
|
||||
// or get_to() instead for correct null handling. See #4864 and #5246.
|
||||
CHECK_THROWS_WITH_AS(std::optional<std::string>(j_null),
|
||||
"[json.exception.type_error.302] type must be string, but is null", json::type_error&);
|
||||
CHECK_THROWS_WITH_AS(std::optional<int>(j_null),
|
||||
"[json.exception.type_error.302] type must be number, but is null", json::type_error&);
|
||||
}
|
||||
|
||||
SECTION("string")
|
||||
@@ -1830,6 +1819,7 @@ TEST_CASE("std::optional")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef JSON_HAS_CPP_17
|
||||
#undef JSON_HAS_CPP_17
|
||||
|
||||
+22
-6
@@ -35,10 +35,10 @@ TEST_CASE("hash<nlohmann::json>")
|
||||
|
||||
// number
|
||||
hashes.insert(std::hash<json> {}(json(0)));
|
||||
hashes.insert(std::hash<json> {}(json(static_cast<unsigned>(0))));
|
||||
hashes.insert(std::hash<json> {}(json(static_cast<unsigned>(0)))); // now same hash as json(0)
|
||||
hashes.insert(std::hash<json> {}(json(0.0))); // now same hash as json(0)
|
||||
|
||||
hashes.insert(std::hash<json> {}(json(-1)));
|
||||
hashes.insert(std::hash<json> {}(json(0.0)));
|
||||
hashes.insert(std::hash<json> {}(json(42.23)));
|
||||
|
||||
// array
|
||||
@@ -60,7 +60,16 @@ TEST_CASE("hash<nlohmann::json>")
|
||||
// discarded
|
||||
hashes.insert(std::hash<json> {}(json(json::value_t::discarded)));
|
||||
|
||||
CHECK(hashes.size() == 21);
|
||||
// Note: json(0), json(0U), and json(0.0) now hash to the same value
|
||||
// (to satisfy the std::hash contract: equal values must hash equally)
|
||||
// So we expect 19 distinct hashes instead of 21
|
||||
CHECK(hashes.size() == 19);
|
||||
|
||||
// Verify the std::hash contract: equal values must hash equally
|
||||
CHECK(std::hash<json> {}(json(0)) == std::hash<json> {}(json(static_cast<unsigned>(0))));
|
||||
CHECK(std::hash<json> {}(json(0)) == std::hash<json> {}(json(0.0)));
|
||||
CHECK(std::hash<json> {}(json(42)) == std::hash<json> {}(json(42u)));
|
||||
CHECK(std::hash<json> {}(json(42)) == std::hash<json> {}(json(42.0)));
|
||||
}
|
||||
|
||||
TEST_CASE("hash<nlohmann::ordered_json>")
|
||||
@@ -84,10 +93,10 @@ TEST_CASE("hash<nlohmann::ordered_json>")
|
||||
|
||||
// number
|
||||
hashes.insert(std::hash<ordered_json> {}(ordered_json(0)));
|
||||
hashes.insert(std::hash<ordered_json> {}(ordered_json(static_cast<unsigned>(0))));
|
||||
hashes.insert(std::hash<ordered_json> {}(ordered_json(static_cast<unsigned>(0)))); // now same hash as ordered_json(0)
|
||||
hashes.insert(std::hash<ordered_json> {}(ordered_json(0.0))); // now same hash as ordered_json(0)
|
||||
|
||||
hashes.insert(std::hash<ordered_json> {}(ordered_json(-1)));
|
||||
hashes.insert(std::hash<ordered_json> {}(ordered_json(0.0)));
|
||||
hashes.insert(std::hash<ordered_json> {}(ordered_json(42.23)));
|
||||
|
||||
// array
|
||||
@@ -109,5 +118,12 @@ TEST_CASE("hash<nlohmann::ordered_json>")
|
||||
// discarded
|
||||
hashes.insert(std::hash<ordered_json> {}(ordered_json(ordered_json::value_t::discarded)));
|
||||
|
||||
CHECK(hashes.size() == 21);
|
||||
// Note: ordered_json(0), ordered_json(0U), and ordered_json(0.0) now hash to the same value
|
||||
CHECK(hashes.size() == 19);
|
||||
|
||||
// Verify the std::hash contract for ordered_json as well
|
||||
CHECK(std::hash<ordered_json> {}(ordered_json(0)) == std::hash<ordered_json> {}(ordered_json(static_cast<unsigned>(0))));
|
||||
CHECK(std::hash<ordered_json> {}(ordered_json(0)) == std::hash<ordered_json> {}(ordered_json(0.0)));
|
||||
CHECK(std::hash<ordered_json> {}(ordered_json(42)) == std::hash<ordered_json> {}(ordered_json(42u)));
|
||||
CHECK(std::hash<ordered_json> {}(ordered_json(42)) == std::hash<ordered_json> {}(ordered_json(42.0)));
|
||||
}
|
||||
|
||||
@@ -942,7 +942,7 @@ TEST_CASE("iterators 2")
|
||||
json j_expected{5, 4, 3, 2, 1};
|
||||
|
||||
auto reversed = j | std::views::reverse;
|
||||
CHECK(reversed == j_expected);
|
||||
CHECK(std::ranges::equal(reversed, j_expected));
|
||||
}
|
||||
|
||||
SECTION("transform")
|
||||
|
||||
Reference in New Issue
Block a user