mirror of
https://github.com/nlohmann/json.git
synced 2026-09-28 02:30:32 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
103b37aa7d | ||
|
|
4671f04372 | ||
|
|
99716a5ade | ||
|
|
d914e3a027 |
@@ -31,45 +31,6 @@ jobs:
|
|||||||
- name: Build
|
- name: Build
|
||||||
run: cmake --build build --target ci_test_gcc
|
run: cmake --build build --target ci_test_gcc
|
||||||
|
|
||||||
ci_meson_install:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- name: Get latest CMake and ninja
|
|
||||||
uses: lukka/get-cmake@fffaaafeea488556c2c12dad60690008bc1caacb # v4.4.2
|
|
||||||
- name: Install Meson
|
|
||||||
run: pip install meson
|
|
||||||
- name: Install with Meson
|
|
||||||
run: |
|
|
||||||
meson setup build-meson --prefix=${{ github.workspace }}/install
|
|
||||||
meson install -C build-meson
|
|
||||||
- name: Use the installed package with find_package
|
|
||||||
run: |
|
|
||||||
cmake -S tests/cmake_import/project -B build-import -DCMAKE_PREFIX_PATH=${{ github.workspace }}/install
|
|
||||||
cmake --build build-import
|
|
||||||
- name: Install with Meson and non-default options
|
|
||||||
run: |
|
|
||||||
meson setup build-meson-options --prefix=${{ github.workspace }}/install-options -DMultipleHeaders=true -DDiagnostics=true -DGlobalUDLs=false
|
|
||||||
meson install -C build-meson-options
|
|
||||||
- name: Check that the options reach the installed files
|
|
||||||
run: |
|
|
||||||
test -d install-options/include/nlohmann/detail
|
|
||||||
cflags=$(PKG_CONFIG_PATH=${{ github.workspace }}/install-options/share/pkgconfig pkg-config --cflags nlohmann_json)
|
|
||||||
echo "$cflags"
|
|
||||||
echo "$cflags" | grep -q -- '-DJSON_DIAGNOSTICS=1'
|
|
||||||
echo "$cflags" | grep -q -- '-DJSON_USE_GLOBAL_UDLS=0'
|
|
||||||
grep -q 'JSON_USE_GLOBAL_UDLS=0;JSON_DIAGNOSTICS=1' install-options/share/cmake/nlohmann_json/nlohmann_jsonTargets.cmake
|
|
||||||
cmake -S tests/cmake_import/project -B build-import-options -DCMAKE_PREFIX_PATH=${{ github.workspace }}/install-options
|
|
||||||
cmake --build build-import-options
|
|
||||||
- name: Install with Meson and the include directory outside the prefix
|
|
||||||
run: |
|
|
||||||
meson setup build-meson-split --prefix=${{ github.workspace }}/install-split --includedir=${{ github.workspace }}/install-split-dev/include
|
|
||||||
meson install -C build-meson-split
|
|
||||||
cmake -S tests/cmake_import/project -B build-import-split -DCMAKE_PREFIX_PATH=${{ github.workspace }}/install-split
|
|
||||||
cmake --build build-import-split
|
|
||||||
|
|
||||||
ci_infer:
|
ci_infer:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
|
|||||||
+1
-24
@@ -168,30 +168,7 @@ if (MSVC)
|
|||||||
)
|
)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
# Install a pkg-config file, so other tools can find this. It carries the same
|
# Install a pkg-config file, so other tools can find this.
|
||||||
# compile definitions as the target above.
|
|
||||||
set(NLOHMANN_JSON_PKGCONFIG_CFLAGS "")
|
|
||||||
if (NOT JSON_GlobalUDLs)
|
|
||||||
string(APPEND NLOHMANN_JSON_PKGCONFIG_CFLAGS " -DJSON_USE_GLOBAL_UDLS=0")
|
|
||||||
endif()
|
|
||||||
if (NOT JSON_ImplicitConversions)
|
|
||||||
string(APPEND NLOHMANN_JSON_PKGCONFIG_CFLAGS " -DJSON_USE_IMPLICIT_CONVERSIONS=0")
|
|
||||||
endif()
|
|
||||||
if (JSON_DisableEnumSerialization)
|
|
||||||
string(APPEND NLOHMANN_JSON_PKGCONFIG_CFLAGS " -DJSON_DISABLE_ENUM_SERIALIZATION=1")
|
|
||||||
endif()
|
|
||||||
if (JSON_Diagnostics)
|
|
||||||
string(APPEND NLOHMANN_JSON_PKGCONFIG_CFLAGS " -DJSON_DIAGNOSTICS=1")
|
|
||||||
endif()
|
|
||||||
if (JSON_Diagnostic_Positions)
|
|
||||||
string(APPEND NLOHMANN_JSON_PKGCONFIG_CFLAGS " -DJSON_DIAGNOSTIC_POSITIONS=1")
|
|
||||||
endif()
|
|
||||||
if (JSON_LegacyDiscardedValueComparison)
|
|
||||||
string(APPEND NLOHMANN_JSON_PKGCONFIG_CFLAGS " -DJSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON=1")
|
|
||||||
endif()
|
|
||||||
if (JSON_StrictNulHandling)
|
|
||||||
string(APPEND NLOHMANN_JSON_PKGCONFIG_CFLAGS " -DJSON_STRICT_NUL_HANDLING=1")
|
|
||||||
endif()
|
|
||||||
configure_file(
|
configure_file(
|
||||||
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/pkg-config.pc.in"
|
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/pkg-config.pc.in"
|
||||||
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc"
|
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc"
|
||||||
|
|||||||
@@ -260,29 +260,9 @@ make BUILD.bazel
|
|||||||
|
|
||||||
The "Check amalgamation" workflow fails if the file is out of date.
|
The "Check amalgamation" workflow fails if the file is out of date.
|
||||||
|
|
||||||
### `meson.build` and `meson_options.txt`
|
### `meson.build`
|
||||||
|
|
||||||
Meson build definitions suitable for use as a subproject ("wrap" in Meson terminology).
|
The build definition for the [Meson](https://mesonbuild.com) build system.
|
||||||
|
|
||||||
Projects wishing to use the wrap can execute:
|
|
||||||
```sh
|
|
||||||
meson wrap install nlohmann_json
|
|
||||||
```
|
|
||||||
|
|
||||||
Which allows Meson to build from source when a system provided dependency isn't available.
|
|
||||||
|
|
||||||
To build directly:
|
|
||||||
```sh
|
|
||||||
meson setup builddir
|
|
||||||
ninja -C builddir
|
|
||||||
```
|
|
||||||
|
|
||||||
`meson_options.txt` defines the options, which mirror the CMake options that change the library's target (for example,
|
|
||||||
`-DDiagnostics=true`). Meson requires this file next to `meson.build`, so it is also part of `include.zip`.
|
|
||||||
|
|
||||||
When installing, `meson.build` installs the headers, a pkg-config file, and the CMake package config files, so that
|
|
||||||
`find_package(nlohmann_json)` works. As Meson cannot generate `nlohmann_jsonTargets.cmake` itself, it is created from
|
|
||||||
the template `cmake/nlohmann_jsonTargets.cmake.in`, which is only used by Meson.
|
|
||||||
|
|
||||||
### `Package.swift`
|
### `Package.swift`
|
||||||
|
|
||||||
|
|||||||
@@ -222,7 +222,7 @@ json.tar.xz:
|
|||||||
# We use `-X` to make the resulting ZIP file reproducible, see
|
# We use `-X` to make the resulting ZIP file reproducible, see
|
||||||
# <https://content.pivotal.io/blog/barriers-to-deterministic-reproducible-zip-files>.
|
# <https://content.pivotal.io/blog/barriers-to-deterministic-reproducible-zip-files>.
|
||||||
include.zip: BUILD.bazel
|
include.zip: BUILD.bazel
|
||||||
zip -9 --recurse-paths -X include.zip $(SRCS) $(AMALGAMATED_FILE) $(AMALGAMATED_FWD_FILE) BUILD.bazel MODULE.bazel meson.build meson_options.txt LICENSE.MIT
|
zip -9 --recurse-paths -X include.zip $(SRCS) $(AMALGAMATED_FILE) $(AMALGAMATED_FWD_FILE) BUILD.bazel MODULE.bazel meson.build LICENSE.MIT
|
||||||
|
|
||||||
# Create the files for a release and add signatures and hashes.
|
# Create the files for a release and add signatures and hashes.
|
||||||
release: include.zip json.tar.xz
|
release: include.zip json.tar.xz
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
# Imported target for installations made with Meson (see meson.build).
|
|
||||||
#
|
|
||||||
# CMake installations generate this file with install(EXPORT ...). Meson cannot
|
|
||||||
# do that, but as the library is header-only, the target only needs an include
|
|
||||||
# directory, the C++ standard, and the compile definitions of the options that
|
|
||||||
# differ from their defaults. Paths are computed relative to this file so that
|
|
||||||
# the installation can be relocated (e.g., into a sysroot), unless includedir or
|
|
||||||
# datadir is outside the prefix.
|
|
||||||
|
|
||||||
if(TARGET @PROJECT_NAME@::@NLOHMANN_JSON_TARGET_NAME@)
|
|
||||||
return()
|
|
||||||
endif()
|
|
||||||
|
|
||||||
get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_DIR}/@NLOHMANN_JSON_CONFIG_TO_PREFIX@" ABSOLUTE)
|
|
||||||
|
|
||||||
add_library(@PROJECT_NAME@::@NLOHMANN_JSON_TARGET_NAME@ INTERFACE IMPORTED)
|
|
||||||
set_target_properties(@PROJECT_NAME@::@NLOHMANN_JSON_TARGET_NAME@ PROPERTIES
|
|
||||||
INTERFACE_INCLUDE_DIRECTORIES "@NLOHMANN_JSON_INCLUDE_DIR@"
|
|
||||||
)
|
|
||||||
if(CMAKE_VERSION VERSION_LESS 3.8)
|
|
||||||
set_target_properties(@PROJECT_NAME@::@NLOHMANN_JSON_TARGET_NAME@ PROPERTIES
|
|
||||||
INTERFACE_COMPILE_FEATURES cxx_range_for
|
|
||||||
)
|
|
||||||
else()
|
|
||||||
set_target_properties(@PROJECT_NAME@::@NLOHMANN_JSON_TARGET_NAME@ PROPERTIES
|
|
||||||
INTERFACE_COMPILE_FEATURES cxx_std_11
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
set(_NLOHMANN_JSON_COMPILE_DEFINITIONS "@NLOHMANN_JSON_COMPILE_DEFINITIONS@")
|
|
||||||
if(_NLOHMANN_JSON_COMPILE_DEFINITIONS)
|
|
||||||
set_target_properties(@PROJECT_NAME@::@NLOHMANN_JSON_TARGET_NAME@ PROPERTIES
|
|
||||||
INTERFACE_COMPILE_DEFINITIONS "${_NLOHMANN_JSON_COMPILE_DEFINITIONS}"
|
|
||||||
)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
unset(_NLOHMANN_JSON_COMPILE_DEFINITIONS)
|
|
||||||
unset(_IMPORT_PREFIX)
|
|
||||||
@@ -4,4 +4,4 @@ includedir=${prefix}/@CMAKE_INSTALL_INCLUDEDIR@
|
|||||||
Name: @PROJECT_NAME@
|
Name: @PROJECT_NAME@
|
||||||
Description: JSON for Modern C++
|
Description: JSON for Modern C++
|
||||||
Version: @PROJECT_VERSION@
|
Version: @PROJECT_VERSION@
|
||||||
Cflags: -I${includedir}@NLOHMANN_JSON_PKGCONFIG_CFLAGS@
|
Cflags: -I${includedir}
|
||||||
|
|||||||
@@ -53,6 +53,8 @@ header. See also the [macro overview page](../../features/macros.md).
|
|||||||
- [**JSON_BRACE_INIT_COPY_SEMANTICS**](json_brace_init_copy_semantics.md) - opt in to copy/move semantics for single-element brace initialization
|
- [**JSON_BRACE_INIT_COPY_SEMANTICS**](json_brace_init_copy_semantics.md) - opt in to copy/move semantics for single-element brace initialization
|
||||||
- [**JSON_DISABLE_ENUM_SERIALIZATION**](json_disable_enum_serialization.md) - switch off default serialization/deserialization functions for enums
|
- [**JSON_DISABLE_ENUM_SERIALIZATION**](json_disable_enum_serialization.md) - switch off default serialization/deserialization functions for enums
|
||||||
- [**JSON_USE_IMPLICIT_CONVERSIONS**](json_use_implicit_conversions.md) - control implicit conversions
|
- [**JSON_USE_IMPLICIT_CONVERSIONS**](json_use_implicit_conversions.md) - control implicit conversions
|
||||||
|
- [**JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS**](json_use_objects_for_enum_keyed_maps.md) - opt in to storing maps with enum
|
||||||
|
keys as objects
|
||||||
|
|
||||||
## Comparison behavior
|
## Comparison behavior
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
# JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
#define JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS /* value */
|
||||||
|
```
|
||||||
|
|
||||||
|
When defined to `1`, maps whose keys are enums (such as `std::map<E, T>` or `std::unordered_map<E, T>`) are stored as
|
||||||
|
JSON objects, using the enum's own conversion for the keys. By default, they are stored as arrays of `[key, value]`
|
||||||
|
pairs.
|
||||||
|
|
||||||
|
## Default definition
|
||||||
|
|
||||||
|
The default value is `0` (disabled — existing behavior is preserved).
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
#define JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS 0
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
!!! note "Background"
|
||||||
|
|
||||||
|
JSON object keys are strings, so a map is only stored as an object if its keys can be converted to a string type.
|
||||||
|
Enums are not, even if [`NLOHMANN_JSON_SERIALIZE_ENUM`](nlohmann_json_serialize_enum.md) maps them to strings, so a
|
||||||
|
map with enum keys becomes an array of `[key, value]` pairs:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[["stopped", "aa"], ["completed", "bb"]]
|
||||||
|
```
|
||||||
|
|
||||||
|
With this macro, the same map becomes an object
|
||||||
|
(see [#4378](https://github.com/nlohmann/json/issues/4378)):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"completed": "bb", "stopped": "aa"}
|
||||||
|
```
|
||||||
|
|
||||||
|
!!! note "Maps with non-unique keys"
|
||||||
|
|
||||||
|
Maps that allow duplicate keys, such as `std::multimap<E, T>` or `std::unordered_multimap<E, T>`, are not affected
|
||||||
|
by the macro and are still stored as arrays of `[key, value]` pairs, as an object cannot hold duplicate keys.
|
||||||
|
|
||||||
|
!!! note "Reading"
|
||||||
|
|
||||||
|
Reading is not affected by the macro: a map with enum keys can always be read from both an array of pairs and an
|
||||||
|
object. For the latter, each key is converted to the enum with its `from_json` function, e.g., the one defined by
|
||||||
|
[`NLOHMANN_JSON_SERIALIZE_ENUM`](nlohmann_json_serialize_enum.md). Data written without the macro can therefore
|
||||||
|
still be read after enabling it.
|
||||||
|
|
||||||
|
!!! warning "Keys must serialize to distinct strings"
|
||||||
|
|
||||||
|
Each key is converted with the enum's `to_json` function. If a key is not converted to a string (for instance, an
|
||||||
|
enum without [`NLOHMANN_JSON_SERIALIZE_ENUM`](nlohmann_json_serialize_enum.md), which is stored as an integer, or an
|
||||||
|
enumerator mapped to `nullptr`), [`type_error.302`](../../home/exceptions.md#jsonexceptiontype_error302) is thrown.
|
||||||
|
If two keys are converted to the same string (for instance, because
|
||||||
|
[`NLOHMANN_JSON_SERIALIZE_ENUM`](nlohmann_json_serialize_enum.md) maps an unlisted enumerator to the first entry),
|
||||||
|
[`type_error.318`](../../home/exceptions.md#jsonexceptiontype_error318) is thrown. In both cases, the target value
|
||||||
|
is not changed.
|
||||||
|
|
||||||
|
!!! warning "Opt-in only"
|
||||||
|
|
||||||
|
This macro must be defined **before** including `<nlohmann/json.hpp>`. Defining it after the include has no effect.
|
||||||
|
|
||||||
|
!!! note "ABI compatibility"
|
||||||
|
|
||||||
|
The value of this macro is encoded in the [namespace](../../features/namespace.md) (tag `_ekmo`), resulting in
|
||||||
|
distinct symbol names. Translation units compiled with and without it can therefore be linked into the same program
|
||||||
|
without One Definition Rule (ODR) violations, but they cannot exchange instances of library types.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
??? example "Default behavior (macro not defined)"
|
||||||
|
|
||||||
|
Without the macro, a map with enum keys is stored as an array of pairs:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
#include <map>
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
|
|
||||||
|
using json = nlohmann::json;
|
||||||
|
|
||||||
|
enum TaskState { TS_STOPPED, TS_RUNNING, TS_COMPLETED };
|
||||||
|
|
||||||
|
NLOHMANN_JSON_SERIALIZE_ENUM(TaskState, {
|
||||||
|
{TS_STOPPED, "stopped"},
|
||||||
|
{TS_RUNNING, "running"},
|
||||||
|
{TS_COMPLETED, "completed"},
|
||||||
|
})
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
std::map<TaskState, std::string> m = {{TS_STOPPED, "aa"}, {TS_COMPLETED, "bb"}};
|
||||||
|
|
||||||
|
json j = m;
|
||||||
|
// j is [["stopped","aa"],["completed","bb"]]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
??? example "Objects for enum-keyed maps (macro defined to 1)"
|
||||||
|
|
||||||
|
With the macro, the same map is stored as an object:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
#define JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS 1
|
||||||
|
#include <map>
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
|
|
||||||
|
using json = nlohmann::json;
|
||||||
|
|
||||||
|
enum TaskState { TS_STOPPED, TS_RUNNING, TS_COMPLETED };
|
||||||
|
|
||||||
|
NLOHMANN_JSON_SERIALIZE_ENUM(TaskState, {
|
||||||
|
{TS_STOPPED, "stopped"},
|
||||||
|
{TS_RUNNING, "running"},
|
||||||
|
{TS_COMPLETED, "completed"},
|
||||||
|
})
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
std::map<TaskState, std::string> m = {{TS_STOPPED, "aa"}, {TS_COMPLETED, "bb"}};
|
||||||
|
|
||||||
|
json j = m;
|
||||||
|
// j is {"completed":"bb","stopped":"aa"}
|
||||||
|
|
||||||
|
auto m2 = j.get<std::map<TaskState, std::string>>();
|
||||||
|
// m2 == m
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## See also
|
||||||
|
|
||||||
|
- [Specializing enum conversion](../../features/enum_conversion.md)
|
||||||
|
- [**NLOHMANN_JSON_SERIALIZE_ENUM**](nlohmann_json_serialize_enum.md) - serialize/deserialize an enum
|
||||||
|
- [**NLOHMANN_JSON_SERIALIZE_ENUM_STRICT**](nlohmann_json_serialize_enum_strict.md) - serialize/deserialize an enum with
|
||||||
|
exceptions
|
||||||
|
|
||||||
|
## Version history
|
||||||
|
|
||||||
|
- Added in version 3.13.0.
|
||||||
@@ -41,6 +41,9 @@ inline void from_json(const BasicJsonType& j, type& e);
|
|||||||
conversion. Select this default pair carefully. See example 1 below.
|
conversion. Select this default pair carefully. See example 1 below.
|
||||||
- If an enum or JSON value is specified in multiple conversions, the first matching conversion from the top of the
|
- If an enum or JSON value is specified in multiple conversions, the first matching conversion from the top of the
|
||||||
list will be returned when converting to or from JSON. See example 2 below.
|
list will be returned when converting to or from JSON. See example 2 below.
|
||||||
|
- Maps with enum keys (e.g., `std::map<ENUM_TYPE, T>`) are stored as arrays of `[key, value]` pairs by default.
|
||||||
|
Define [`JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS`](json_use_objects_for_enum_keyed_maps.md) to store them as objects
|
||||||
|
with the converted keys. Such maps can be read from both forms.
|
||||||
|
|
||||||
## Examples
|
## Examples
|
||||||
|
|
||||||
@@ -80,6 +83,7 @@ inline void from_json(const BasicJsonType& j, type& e);
|
|||||||
- [Specializing enum conversion](../../features/enum_conversion.md)
|
- [Specializing enum conversion](../../features/enum_conversion.md)
|
||||||
- [`NLOHMANN_JSON_SERIALIZE_ENUM_STRICT`](./nlohmann_json_serialize_enum_strict.md)
|
- [`NLOHMANN_JSON_SERIALIZE_ENUM_STRICT`](./nlohmann_json_serialize_enum_strict.md)
|
||||||
- [`JSON_DISABLE_ENUM_SERIALIZATION`](json_disable_enum_serialization.md)
|
- [`JSON_DISABLE_ENUM_SERIALIZATION`](json_disable_enum_serialization.md)
|
||||||
|
- [`JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS`](json_use_objects_for_enum_keyed_maps.md)
|
||||||
|
|
||||||
## Version history
|
## Version history
|
||||||
|
|
||||||
|
|||||||
@@ -44,6 +44,9 @@ inline void from_json(const BasicJsonType& j, type& e);
|
|||||||
`"enum value out of range for <type>"`.
|
`"enum value out of range for <type>"`.
|
||||||
- If an enum or JSON value is specified in multiple conversions, the first matching conversion from the top of the
|
- If an enum or JSON value is specified in multiple conversions, the first matching conversion from the top of the
|
||||||
list will be returned when converting to or from JSON. See example 2 below.
|
list will be returned when converting to or from JSON. See example 2 below.
|
||||||
|
- Maps with enum keys (e.g., `std::map<ENUM_TYPE, T>`) are stored as arrays of `[key, value]` pairs by default.
|
||||||
|
Define [`JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS`](json_use_objects_for_enum_keyed_maps.md) to store them as objects
|
||||||
|
with the converted keys. Such maps can be read from both forms.
|
||||||
|
|
||||||
## Examples
|
## Examples
|
||||||
|
|
||||||
@@ -99,6 +102,7 @@ inline void from_json(const BasicJsonType& j, type& e);
|
|||||||
- [Specializing enum conversion](../../features/enum_conversion.md)
|
- [Specializing enum conversion](../../features/enum_conversion.md)
|
||||||
- [`NLOHMANN_JSON_SERIALIZE_ENUM`](./nlohmann_json_serialize_enum.md)
|
- [`NLOHMANN_JSON_SERIALIZE_ENUM`](./nlohmann_json_serialize_enum.md)
|
||||||
- [`JSON_DISABLE_ENUM_SERIALIZATION`](json_disable_enum_serialization.md)
|
- [`JSON_DISABLE_ENUM_SERIALIZATION`](json_disable_enum_serialization.md)
|
||||||
|
- [`JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS`](json_use_objects_for_enum_keyed_maps.md)
|
||||||
|
|
||||||
## Version history
|
## Version history
|
||||||
|
|
||||||
|
|||||||
@@ -43,6 +43,23 @@ json jPi = 3.14;
|
|||||||
assert(jPi.get<TaskState>() == TS_INVALID );
|
assert(jPi.get<TaskState>() == TS_INVALID );
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Maps with enum keys
|
||||||
|
|
||||||
|
By default, maps with enum keys, such as `std::map<TaskState, std::string>`, are stored as arrays of `[key, value]`
|
||||||
|
pairs, because JSON object keys must be strings. Define
|
||||||
|
[`JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS`](../api/macros/json_use_objects_for_enum_keyed_maps.md) before including the
|
||||||
|
library to store them as objects, with the keys converted by the enum's `to_json()` function:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
std::map<TaskState, std::string> m = {{TS_STOPPED, "aa"}, {TS_COMPLETED, "bb"}};
|
||||||
|
|
||||||
|
json j = m;
|
||||||
|
// default: [["stopped","aa"],["completed","bb"]]
|
||||||
|
// with JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS: {"completed":"bb","stopped":"aa"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Either form can be read back, with or without the macro.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
|
|
||||||
Just as in [Arbitrary Type Conversions](arbitrary_types.md) above,
|
Just as in [Arbitrary Type Conversions](arbitrary_types.md) above,
|
||||||
|
|||||||
@@ -167,6 +167,13 @@ behavior is deprecated and switched off (`0`) by default.
|
|||||||
|
|
||||||
See [full documentation of `JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON`](../api/macros/json_use_legacy_discarded_value_comparison.md).
|
See [full documentation of `JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON`](../api/macros/json_use_legacy_discarded_value_comparison.md).
|
||||||
|
|
||||||
|
## `JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS`
|
||||||
|
|
||||||
|
When defined to `1`, maps with enum keys (e.g., `std::map<E, T>`) are stored as objects, using the enum's conversion for
|
||||||
|
the keys, instead of arrays of `[key, value]` pairs. It is switched off (`0`) by default.
|
||||||
|
|
||||||
|
See [full documentation of `JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS`](../api/macros/json_use_objects_for_enum_keyed_maps.md).
|
||||||
|
|
||||||
## `JSON_USE_SIMDUTF`
|
## `JSON_USE_SIMDUTF`
|
||||||
|
|
||||||
When defined, UTF-8 validation of JSON strings read from contiguous byte input is delegated to the
|
When defined, UTF-8 validation of JSON strings read from contiguous byte input is delegated to the
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ The complete default namespace name is derived as follows:
|
|||||||
`_bics`.
|
`_bics`.
|
||||||
- [`JSON_PRECISE_STREAM_POSITION`](../api/macros/json_precise_stream_position.md) defined non-zero appends `_psp`.
|
- [`JSON_PRECISE_STREAM_POSITION`](../api/macros/json_precise_stream_position.md) defined non-zero appends `_psp`.
|
||||||
- [`JSON_STRICT_NUL_HANDLING`](../api/macros/json_strict_nul_handling.md) defined non-zero appends `_snul`.
|
- [`JSON_STRICT_NUL_HANDLING`](../api/macros/json_strict_nul_handling.md) defined non-zero appends `_snul`.
|
||||||
|
- [`JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS`](../api/macros/json_use_objects_for_enum_keyed_maps.md) defined non-zero
|
||||||
|
appends `_ekmo`.
|
||||||
- The inline namespace ends with the suffix `_v` followed by the 3 components of the version number separated by
|
- The inline namespace ends with the suffix `_v` followed by the 3 components of the version number separated by
|
||||||
underscores. To omit the version component, see [Disabling the version component](#disabling-the-version-component)
|
underscores. To omit the version component, see [Disabling the version component](#disabling-the-version-component)
|
||||||
below.
|
below.
|
||||||
|
|||||||
@@ -589,6 +589,9 @@ During implicit or explicit value conversion, the JSON type must be compatible w
|
|||||||
[json.exception.type_error.302] type must be string, but is object
|
[json.exception.type_error.302] type must be string, but is object
|
||||||
```
|
```
|
||||||
|
|
||||||
|
This exception is also thrown with [`JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS`](../api/macros/json_use_objects_for_enum_keyed_maps.md)
|
||||||
|
if a key of a map with enum keys is not converted to a string, for instance, because the enum is stored as an integer.
|
||||||
|
|
||||||
### json.exception.type_error.303
|
### json.exception.type_error.303
|
||||||
|
|
||||||
To retrieve a reference to a value stored in a `basic_json` object with `get_ref`, the type of the reference must match the value type. For instance, for a JSON array, the `ReferenceType` must be `array_t &`.
|
To retrieve a reference to a value stored in a `basic_json` object with `get_ref`, the type of the reference must match the value type. For instance, for a JSON array, the `ReferenceType` must be `array_t &`.
|
||||||
@@ -775,6 +778,19 @@ The dynamic type of the object cannot be represented in the requested serializat
|
|||||||
|
|
||||||
Encapsulate the JSON value in an object. That is, instead of serializing `#!json true`, serialize `#!json {"value": true}`
|
Encapsulate the JSON value in an object. That is, instead of serializing `#!json true`, serialize `#!json {"value": true}`
|
||||||
|
|
||||||
|
### json.exception.type_error.318
|
||||||
|
|
||||||
|
With [`JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS`](../api/macros/json_use_objects_for_enum_keyed_maps.md), a map with enum
|
||||||
|
keys is stored as an object. This exception is thrown if two of its keys are converted to the same string, so one of the
|
||||||
|
entries would be lost. This happens, for instance, if [`NLOHMANN_JSON_SERIALIZE_ENUM`](../api/macros/nlohmann_json_serialize_enum.md)
|
||||||
|
does not list an enumerator and it is therefore converted like the first listed one.
|
||||||
|
|
||||||
|
!!! failure "Example message"
|
||||||
|
|
||||||
|
```
|
||||||
|
[json.exception.type_error.318] duplicate object key 'red'
|
||||||
|
```
|
||||||
|
|
||||||
## Out of range
|
## Out of range
|
||||||
|
|
||||||
This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance, in the case of array indices or nonexisting object keys.
|
This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance, in the case of array indices or nonexisting object keys.
|
||||||
|
|||||||
@@ -121,23 +121,10 @@ meson wrap install nlohmann_json
|
|||||||
Please see the Meson project for any issues regarding the packaging.
|
Please see the Meson project for any issues regarding the packaging.
|
||||||
|
|
||||||
The provided `meson.build` can also be used as an alternative to CMake for installing `nlohmann_json` system-wide in
|
The provided `meson.build` can also be used as an alternative to CMake for installing `nlohmann_json` system-wide in
|
||||||
which case a pkg-config file and the CMake package config files are installed. To use it, have your build system require
|
which case a pkg-config file is installed. To use it, have your build system require the `nlohmann_json`
|
||||||
the `nlohmann_json` pkg-config dependency, or use [`find_package(nlohmann_json)`](cmake.md#external) in CMake. In Meson,
|
pkg-config dependency. In Meson, it is preferred to use the
|
||||||
it is preferred to use the [`dependency()`](https://mesonbuild.com/Reference-manual.html#dependency) object with a
|
[`dependency()`](https://mesonbuild.com/Reference-manual.html#dependency) object with a subproject fallback, rather than
|
||||||
subproject fallback, rather than using the subproject directly.
|
using the subproject directly.
|
||||||
|
|
||||||
The options that change the library's configuration are available in Meson as well, named like the
|
|
||||||
[CMake options](cmake.md#cmake-options) without the `JSON_` prefix: `MultipleHeaders`, `GlobalUDLs`,
|
|
||||||
`ImplicitConversions`, `DisableEnumSerialization`, `Diagnostics`, `Diagnostic_Positions`,
|
|
||||||
`LegacyDiscardedValueComparison`, and `StrictNulHandling`. They have the same defaults as in CMake, except that
|
|
||||||
`MultipleHeaders` is `false`. Set them with `-D` when setting up the build, or with the subproject name as prefix when
|
|
||||||
the library is used as a subproject:
|
|
||||||
|
|
||||||
```shell
|
|
||||||
meson setup build -Dnlohmann_json:Diagnostics=true
|
|
||||||
```
|
|
||||||
|
|
||||||
The resulting compile definitions are part of the Meson dependency, the pkg-config file, and the CMake target.
|
|
||||||
|
|
||||||
??? example "Example: Wrap"
|
??? example "Example: Wrap"
|
||||||
|
|
||||||
|
|||||||
@@ -303,6 +303,7 @@ nav:
|
|||||||
- 'JSON_USE_GLOBAL_UDLS': api/macros/json_use_global_udls.md
|
- 'JSON_USE_GLOBAL_UDLS': api/macros/json_use_global_udls.md
|
||||||
- 'JSON_USE_IMPLICIT_CONVERSIONS': api/macros/json_use_implicit_conversions.md
|
- 'JSON_USE_IMPLICIT_CONVERSIONS': api/macros/json_use_implicit_conversions.md
|
||||||
- 'JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON': api/macros/json_use_legacy_discarded_value_comparison.md
|
- 'JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON': api/macros/json_use_legacy_discarded_value_comparison.md
|
||||||
|
- 'JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS': api/macros/json_use_objects_for_enum_keyed_maps.md
|
||||||
- 'JSON_USE_SIMDUTF': api/macros/json_use_simdutf.md
|
- 'JSON_USE_SIMDUTF': api/macros/json_use_simdutf.md
|
||||||
- 'NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE, NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE': api/macros/nlohmann_define_derived_type.md
|
- 'NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE, NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_DERIVED_TYPE_INTRUSIVE_ONLY_SERIALIZE, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_DERIVED_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE': api/macros/nlohmann_define_derived_type.md
|
||||||
- 'NLOHMANN_DEFINE_TYPE_INTRUSIVE, NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE': api/macros/nlohmann_define_type_intrusive.md
|
- 'NLOHMANN_DEFINE_TYPE_INTRUSIVE, NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT, NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE': api/macros/nlohmann_define_type_intrusive.md
|
||||||
|
|||||||
@@ -46,6 +46,10 @@
|
|||||||
#define JSON_STRICT_NUL_HANDLING 0
|
#define JSON_STRICT_NUL_HANDLING 0
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#ifndef JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
#define JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS 0
|
||||||
|
#endif
|
||||||
|
|
||||||
#if JSON_DIAGNOSTICS
|
#if JSON_DIAGNOSTICS
|
||||||
#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag
|
#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag
|
||||||
#else
|
#else
|
||||||
@@ -82,14 +86,20 @@
|
|||||||
#define NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING
|
#define NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
#define NLOHMANN_JSON_ABI_TAG_OBJECTS_FOR_ENUM_KEYED_MAPS _ekmo
|
||||||
|
#else
|
||||||
|
#define NLOHMANN_JSON_ABI_TAG_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
#endif
|
||||||
|
|
||||||
#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION
|
#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION
|
||||||
#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0
|
#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Construct the namespace ABI tags component
|
// Construct the namespace ABI tags component
|
||||||
#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c, d, e, f) json_abi ## a ## b ## c ## d ## e ## f
|
#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c, d, e, f, g) json_abi ## a ## b ## c ## d ## e ## f ## g
|
||||||
#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b, c, d, e, f) \
|
#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b, c, d, e, f, g) \
|
||||||
NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c, d, e, f)
|
NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c, d, e, f, g)
|
||||||
|
|
||||||
#define NLOHMANN_JSON_ABI_TAGS \
|
#define NLOHMANN_JSON_ABI_TAGS \
|
||||||
NLOHMANN_JSON_ABI_TAGS_CONCAT( \
|
NLOHMANN_JSON_ABI_TAGS_CONCAT( \
|
||||||
@@ -98,7 +108,8 @@
|
|||||||
NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS, \
|
NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS, \
|
||||||
NLOHMANN_JSON_ABI_TAG_BRACE_INIT_COPY_SEMANTICS, \
|
NLOHMANN_JSON_ABI_TAG_BRACE_INIT_COPY_SEMANTICS, \
|
||||||
NLOHMANN_JSON_ABI_TAG_PRECISE_STREAM_POSITION, \
|
NLOHMANN_JSON_ABI_TAG_PRECISE_STREAM_POSITION, \
|
||||||
NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING)
|
NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING, \
|
||||||
|
NLOHMANN_JSON_ABI_TAG_OBJECTS_FOR_ENUM_KEYED_MAPS)
|
||||||
|
|
||||||
// Construct the namespace version component
|
// Construct the namespace version component
|
||||||
#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \
|
#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \
|
||||||
|
|||||||
@@ -550,11 +550,40 @@ auto from_json(BasicJsonType&& j, TupleRelated&& t)
|
|||||||
return from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {});
|
return from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// read a map with enum keys from an object, using the enum's own from_json for
|
||||||
|
// the keys (e.g., from NLOHMANN_JSON_SERIALIZE_ENUM); this is the form written
|
||||||
|
// with JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
template<typename BasicJsonType, typename Map>
|
||||||
|
inline bool from_json_enum_keyed_object(const BasicJsonType& j, Map& m, std::true_type /*key is enum*/)
|
||||||
|
{
|
||||||
|
if (!j.is_object())
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
m.clear();
|
||||||
|
for (const auto& p : *j.template get_ptr<const typename BasicJsonType::object_t*>())
|
||||||
|
{
|
||||||
|
m.emplace(BasicJsonType(p.first).template get<typename Map::key_type>(), p.second.template get<typename Map::mapped_type>());
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename BasicJsonType, typename Map>
|
||||||
|
inline bool from_json_enum_keyed_object(const BasicJsonType& /*j*/, Map& /*m*/, std::false_type /*key is enum*/)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
|
template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
|
||||||
typename = enable_if_t < !std::is_constructible <
|
typename = enable_if_t < !std::is_constructible <
|
||||||
typename BasicJsonType::string_t, Key >::value >>
|
typename BasicJsonType::string_t, Key >::value >>
|
||||||
inline void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
|
inline void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
|
||||||
{
|
{
|
||||||
|
// NOLINTNEXTLINE(modernize-type-traits) we use C++11
|
||||||
|
if (from_json_enum_keyed_object(j, m, std::is_enum<Key> {}))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
||||||
{
|
{
|
||||||
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
||||||
@@ -575,6 +604,11 @@ template < typename BasicJsonType, typename Key, typename Value, typename Hash,
|
|||||||
typename BasicJsonType::string_t, Key >::value >>
|
typename BasicJsonType::string_t, Key >::value >>
|
||||||
inline void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
|
inline void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
|
||||||
{
|
{
|
||||||
|
// NOLINTNEXTLINE(modernize-type-traits) we use C++11
|
||||||
|
if (from_json_enum_keyed_object(j, m, std::is_enum<Key> {}))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
||||||
{
|
{
|
||||||
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
||||||
|
|||||||
@@ -23,6 +23,7 @@
|
|||||||
#include <valarray> // valarray
|
#include <valarray> // valarray
|
||||||
#include <vector> // vector
|
#include <vector> // vector
|
||||||
|
|
||||||
|
#include <nlohmann/detail/exceptions.hpp>
|
||||||
#include <nlohmann/detail/iterators/iteration_proxy.hpp>
|
#include <nlohmann/detail/iterators/iteration_proxy.hpp>
|
||||||
#include <nlohmann/detail/meta/cpp_future.hpp>
|
#include <nlohmann/detail/meta/cpp_future.hpp>
|
||||||
#include <nlohmann/detail/meta/std_fs.hpp>
|
#include <nlohmann/detail/meta/std_fs.hpp>
|
||||||
@@ -381,6 +382,9 @@ template < typename BasicJsonType, typename CompatibleArrayType,
|
|||||||
!is_basic_json<CompatibleArrayType>::value
|
!is_basic_json<CompatibleArrayType>::value
|
||||||
#if JSON_HAS_RANGES && !defined(__MINGW32__)
|
#if JSON_HAS_RANGES && !defined(__MINGW32__)
|
||||||
&& !is_compatible_range_view<CompatibleArrayType>::value
|
&& !is_compatible_range_view<CompatibleArrayType>::value
|
||||||
|
#endif
|
||||||
|
#if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
&& !is_enum_keyed_map<CompatibleArrayType>::value
|
||||||
#endif
|
#endif
|
||||||
,
|
,
|
||||||
int > = 0 >
|
int > = 0 >
|
||||||
@@ -435,6 +439,33 @@ inline void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
|
|||||||
external_constructor<value_t::object>::construct(j, obj);
|
external_constructor<value_t::object>::construct(j, obj);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
// store a map with enum keys as an object, using the enum's own to_json for the
|
||||||
|
// keys (e.g., from NLOHMANN_JSON_SERIALIZE_ENUM); without the macro, such maps
|
||||||
|
// are stored as arrays of [key, value] pairs
|
||||||
|
template < typename BasicJsonType, typename EnumKeyedMap,
|
||||||
|
enable_if_t < is_enum_keyed_map<EnumKeyedMap>::value&& !is_basic_json<EnumKeyedMap>::value, int > = 0 >
|
||||||
|
inline void to_json(BasicJsonType& j, const EnumKeyedMap& map)
|
||||||
|
{
|
||||||
|
typename BasicJsonType::object_t obj;
|
||||||
|
for (const auto& p : map)
|
||||||
|
{
|
||||||
|
BasicJsonType key = p.first;
|
||||||
|
if (JSON_HEDLEY_UNLIKELY(!key.is_string()))
|
||||||
|
{
|
||||||
|
JSON_THROW(type_error::create(302, concat("type must be string, but is ", key.type_name()), &key));
|
||||||
|
}
|
||||||
|
|
||||||
|
auto& key_string = *key.template get_ptr<typename BasicJsonType::string_t*>();
|
||||||
|
if (JSON_HEDLEY_UNLIKELY(!obj.emplace(key_string, BasicJsonType(p.second)).second))
|
||||||
|
{
|
||||||
|
JSON_THROW(type_error::create(318, concat("duplicate object key '", key_string, "'"), &key));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
external_constructor<value_t::object>::construct(j, std::move(obj));
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
template<typename BasicJsonType>
|
template<typename BasicJsonType>
|
||||||
inline void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
|
inline void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -46,6 +46,7 @@
|
|||||||
#undef JSON_BRACE_INIT_COPY_SEMANTICS
|
#undef JSON_BRACE_INIT_COPY_SEMANTICS
|
||||||
#undef JSON_PRECISE_STREAM_POSITION
|
#undef JSON_PRECISE_STREAM_POSITION
|
||||||
#undef JSON_STRICT_NUL_HANDLING
|
#undef JSON_STRICT_NUL_HANDLING
|
||||||
|
#undef JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
|
#include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
|
||||||
|
|||||||
@@ -400,6 +400,30 @@ template<typename BasicJsonType, typename CompatibleObjectType>
|
|||||||
struct is_compatible_object_type
|
struct is_compatible_object_type
|
||||||
: is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
|
: is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
using insert_result_t = decltype(std::declval<T&>().insert(std::declval<const value_type_t<T>&>()));
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
using insert_result_second_t = decltype(std::declval<T&>().insert(std::declval<const value_type_t<T>&>()).second);
|
||||||
|
|
||||||
|
// a map-like type (std::map, std::unordered_map, ...) whose keys are enums; see
|
||||||
|
// JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
template<typename T, typename = void>
|
||||||
|
struct is_enum_keyed_map : std::false_type {};
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
struct is_enum_keyed_map <
|
||||||
|
T, enable_if_t < is_detected<mapped_type_t, T>::value&&
|
||||||
|
is_detected<key_type_t, T>::value >>
|
||||||
|
{
|
||||||
|
// maps with non-unique keys (std::multimap, std::unordered_multimap, ...)
|
||||||
|
// are excluded, because an object cannot hold duplicate keys; they are
|
||||||
|
// detected by insert() returning an iterator instead of a pair<iterator, bool>
|
||||||
|
// NOLINTNEXTLINE(modernize-type-traits) we use C++11
|
||||||
|
static constexpr bool value = std::is_enum<typename T::key_type>::value &&
|
||||||
|
!(is_detected<insert_result_t, T>::value && !is_detected<insert_result_second_t, T>::value);
|
||||||
|
};
|
||||||
|
|
||||||
template<typename BasicJsonType, typename ConstructibleObjectType,
|
template<typename BasicJsonType, typename ConstructibleObjectType,
|
||||||
typename = void>
|
typename = void>
|
||||||
struct is_constructible_object_type_impl : std::false_type {};
|
struct is_constructible_object_type_impl : std::false_type {};
|
||||||
|
|||||||
+8
-96
@@ -2,111 +2,23 @@ project('nlohmann_json',
|
|||||||
'cpp',
|
'cpp',
|
||||||
version : '3.12.0',
|
version : '3.12.0',
|
||||||
license : 'MIT',
|
license : 'MIT',
|
||||||
meson_version : '>= 0.64',
|
|
||||||
default_options: ['cpp_std=c++11'],
|
|
||||||
)
|
)
|
||||||
|
|
||||||
if get_option('MultipleHeaders')
|
|
||||||
incdir = 'include'
|
|
||||||
else
|
|
||||||
incdir = 'single_include'
|
|
||||||
endif
|
|
||||||
|
|
||||||
# The same compile definitions as the CMake target (see target_compile_definitions
|
|
||||||
# in CMakeLists.txt): only an option that differs from its default adds one.
|
|
||||||
json_defines = []
|
|
||||||
if not get_option('GlobalUDLs')
|
|
||||||
json_defines += 'JSON_USE_GLOBAL_UDLS=0'
|
|
||||||
endif
|
|
||||||
if not get_option('ImplicitConversions')
|
|
||||||
json_defines += 'JSON_USE_IMPLICIT_CONVERSIONS=0'
|
|
||||||
endif
|
|
||||||
if get_option('DisableEnumSerialization')
|
|
||||||
json_defines += 'JSON_DISABLE_ENUM_SERIALIZATION=1'
|
|
||||||
endif
|
|
||||||
if get_option('Diagnostics')
|
|
||||||
json_defines += 'JSON_DIAGNOSTICS=1'
|
|
||||||
endif
|
|
||||||
if get_option('Diagnostic_Positions')
|
|
||||||
json_defines += 'JSON_DIAGNOSTIC_POSITIONS=1'
|
|
||||||
endif
|
|
||||||
if get_option('LegacyDiscardedValueComparison')
|
|
||||||
json_defines += 'JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON=1'
|
|
||||||
endif
|
|
||||||
if get_option('StrictNulHandling')
|
|
||||||
json_defines += 'JSON_STRICT_NUL_HANDLING=1'
|
|
||||||
endif
|
|
||||||
|
|
||||||
cpp_args = []
|
|
||||||
foreach define : json_defines
|
|
||||||
cpp_args += '-D' + define
|
|
||||||
endforeach
|
|
||||||
|
|
||||||
nlohmann_json_dep = declare_dependency(
|
nlohmann_json_dep = declare_dependency(
|
||||||
compile_args: cpp_args,
|
include_directories: include_directories('single_include')
|
||||||
include_directories: include_directories(incdir)
|
|
||||||
)
|
)
|
||||||
meson.override_dependency('nlohmann_json', nlohmann_json_dep)
|
|
||||||
|
|
||||||
# The multi-header version under the name earlier versions of this file used
|
|
||||||
nlohmann_json_multiple_headers = declare_dependency(
|
nlohmann_json_multiple_headers = declare_dependency(
|
||||||
compile_args: cpp_args,
|
|
||||||
include_directories: include_directories('include')
|
include_directories: include_directories('include')
|
||||||
)
|
)
|
||||||
|
|
||||||
if not meson.is_subproject()
|
if not meson.is_subproject()
|
||||||
install_subdir(
|
install_headers('single_include/nlohmann/json.hpp', subdir: 'nlohmann')
|
||||||
incdir / 'nlohmann',
|
install_headers('single_include/nlohmann/json_fwd.hpp', subdir: 'nlohmann')
|
||||||
install_dir: get_option('includedir'),
|
|
||||||
install_tag: 'devel',
|
|
||||||
)
|
|
||||||
|
|
||||||
pkgc = import('pkgconfig')
|
pkgc = import('pkgconfig')
|
||||||
pkgc.generate(name: 'nlohmann_json',
|
pkgc.generate(name: 'nlohmann_json',
|
||||||
version: meson.project_version(),
|
version: meson.project_version(),
|
||||||
description: 'JSON for Modern C++',
|
description: 'JSON for Modern C++'
|
||||||
extra_cflags: cpp_args,
|
)
|
||||||
install_dir: get_option('datadir') / 'pkgconfig',
|
|
||||||
)
|
|
||||||
|
|
||||||
# CMake package config files, so that find_package(nlohmann_json) works. The
|
|
||||||
# include directory is given relative to the config files, so that the
|
|
||||||
# installation can be relocated. This is not possible if includedir or datadir
|
|
||||||
# is an absolute path outside the prefix (e.g., with the separate outputs of
|
|
||||||
# Nix); then the absolute include directory is used, as CMake does.
|
|
||||||
fs = import('fs')
|
|
||||||
cmake_install_dir = get_option('datadir') / 'cmake' / meson.project_name()
|
|
||||||
cmake_to_prefix = []
|
|
||||||
if fs.is_absolute(get_option('includedir')) or fs.is_absolute(cmake_install_dir)
|
|
||||||
cmake_include_dir = (get_option('prefix') / get_option('includedir')).replace('\\', '/')
|
|
||||||
else
|
|
||||||
foreach component : cmake_install_dir.split('/')
|
|
||||||
cmake_to_prefix += '..'
|
|
||||||
endforeach
|
|
||||||
cmake_include_dir = '${_IMPORT_PREFIX}/' + get_option('includedir')
|
|
||||||
endif
|
|
||||||
|
|
||||||
cmake_conf = configuration_data()
|
|
||||||
cmake_conf.set('PROJECT_NAME', meson.project_name())
|
|
||||||
cmake_conf.set('PROJECT_VERSION', meson.project_version())
|
|
||||||
cmake_conf.set('PROJECT_VERSION_MAJOR', meson.project_version().split('.')[0])
|
|
||||||
cmake_conf.set('NLOHMANN_JSON_TARGET_NAME', meson.project_name())
|
|
||||||
cmake_conf.set('NLOHMANN_JSON_TARGETS_EXPORT_NAME', meson.project_name() + 'Targets')
|
|
||||||
cmake_conf.set('NLOHMANN_JSON_INCLUDE_DIR', cmake_include_dir)
|
|
||||||
cmake_conf.set('NLOHMANN_JSON_CONFIG_TO_PREFIX', '/'.join(cmake_to_prefix))
|
|
||||||
cmake_conf.set('NLOHMANN_JSON_COMPILE_DEFINITIONS', ';'.join(json_defines))
|
|
||||||
|
|
||||||
foreach cmake_file : [
|
|
||||||
['cmake/config.cmake.in', 'nlohmann_jsonConfig.cmake'],
|
|
||||||
['cmake/nlohmann_jsonConfigVersion.cmake.in', 'nlohmann_jsonConfigVersion.cmake'],
|
|
||||||
['cmake/nlohmann_jsonTargets.cmake.in', 'nlohmann_jsonTargets.cmake'],
|
|
||||||
]
|
|
||||||
configure_file(
|
|
||||||
input: cmake_file[0],
|
|
||||||
output: cmake_file[1],
|
|
||||||
configuration: cmake_conf,
|
|
||||||
format: 'cmake@',
|
|
||||||
install_dir: cmake_install_dir,
|
|
||||||
)
|
|
||||||
endforeach
|
|
||||||
endif
|
endif
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
option(
|
|
||||||
'MultipleHeaders',
|
|
||||||
type: 'boolean',
|
|
||||||
value: false,
|
|
||||||
description: 'Use non-amalgamated version of the library',
|
|
||||||
)
|
|
||||||
option(
|
|
||||||
'GlobalUDLs',
|
|
||||||
type: 'boolean',
|
|
||||||
value: true,
|
|
||||||
description: 'Place user-defined string literals in the global namespace',
|
|
||||||
)
|
|
||||||
option(
|
|
||||||
'ImplicitConversions',
|
|
||||||
type: 'boolean',
|
|
||||||
value: true,
|
|
||||||
description: 'Enable implicit conversions',
|
|
||||||
)
|
|
||||||
option(
|
|
||||||
'DisableEnumSerialization',
|
|
||||||
type: 'boolean',
|
|
||||||
value: false,
|
|
||||||
description: 'Disable default integer enum serialization',
|
|
||||||
)
|
|
||||||
option(
|
|
||||||
'Diagnostics',
|
|
||||||
type: 'boolean',
|
|
||||||
value: false,
|
|
||||||
description: 'Use extended diagnostic messages',
|
|
||||||
)
|
|
||||||
option(
|
|
||||||
'Diagnostic_Positions',
|
|
||||||
type: 'boolean',
|
|
||||||
value: false,
|
|
||||||
description: 'Enable diagnostic positions',
|
|
||||||
)
|
|
||||||
option(
|
|
||||||
'LegacyDiscardedValueComparison',
|
|
||||||
type: 'boolean',
|
|
||||||
value: false,
|
|
||||||
description: 'Enable legacy discarded value comparison',
|
|
||||||
)
|
|
||||||
option(
|
|
||||||
'StrictNulHandling',
|
|
||||||
type: 'boolean',
|
|
||||||
value: false,
|
|
||||||
description: 'Enable strict NUL-byte handling',
|
|
||||||
)
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -103,6 +103,10 @@
|
|||||||
#define JSON_STRICT_NUL_HANDLING 0
|
#define JSON_STRICT_NUL_HANDLING 0
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#ifndef JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
#define JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS 0
|
||||||
|
#endif
|
||||||
|
|
||||||
#if JSON_DIAGNOSTICS
|
#if JSON_DIAGNOSTICS
|
||||||
#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag
|
#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag
|
||||||
#else
|
#else
|
||||||
@@ -139,14 +143,20 @@
|
|||||||
#define NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING
|
#define NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
#define NLOHMANN_JSON_ABI_TAG_OBJECTS_FOR_ENUM_KEYED_MAPS _ekmo
|
||||||
|
#else
|
||||||
|
#define NLOHMANN_JSON_ABI_TAG_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
#endif
|
||||||
|
|
||||||
#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION
|
#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION
|
||||||
#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0
|
#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Construct the namespace ABI tags component
|
// Construct the namespace ABI tags component
|
||||||
#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c, d, e, f) json_abi ## a ## b ## c ## d ## e ## f
|
#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c, d, e, f, g) json_abi ## a ## b ## c ## d ## e ## f ## g
|
||||||
#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b, c, d, e, f) \
|
#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b, c, d, e, f, g) \
|
||||||
NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c, d, e, f)
|
NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c, d, e, f, g)
|
||||||
|
|
||||||
#define NLOHMANN_JSON_ABI_TAGS \
|
#define NLOHMANN_JSON_ABI_TAGS \
|
||||||
NLOHMANN_JSON_ABI_TAGS_CONCAT( \
|
NLOHMANN_JSON_ABI_TAGS_CONCAT( \
|
||||||
@@ -155,7 +165,8 @@
|
|||||||
NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS, \
|
NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS, \
|
||||||
NLOHMANN_JSON_ABI_TAG_BRACE_INIT_COPY_SEMANTICS, \
|
NLOHMANN_JSON_ABI_TAG_BRACE_INIT_COPY_SEMANTICS, \
|
||||||
NLOHMANN_JSON_ABI_TAG_PRECISE_STREAM_POSITION, \
|
NLOHMANN_JSON_ABI_TAG_PRECISE_STREAM_POSITION, \
|
||||||
NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING)
|
NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING, \
|
||||||
|
NLOHMANN_JSON_ABI_TAG_OBJECTS_FOR_ENUM_KEYED_MAPS)
|
||||||
|
|
||||||
// Construct the namespace version component
|
// Construct the namespace version component
|
||||||
#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \
|
#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \
|
||||||
@@ -4410,6 +4421,30 @@ template<typename BasicJsonType, typename CompatibleObjectType>
|
|||||||
struct is_compatible_object_type
|
struct is_compatible_object_type
|
||||||
: is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
|
: is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {};
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
using insert_result_t = decltype(std::declval<T&>().insert(std::declval<const value_type_t<T>&>()));
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
using insert_result_second_t = decltype(std::declval<T&>().insert(std::declval<const value_type_t<T>&>()).second);
|
||||||
|
|
||||||
|
// a map-like type (std::map, std::unordered_map, ...) whose keys are enums; see
|
||||||
|
// JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
template<typename T, typename = void>
|
||||||
|
struct is_enum_keyed_map : std::false_type {};
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
struct is_enum_keyed_map <
|
||||||
|
T, enable_if_t < is_detected<mapped_type_t, T>::value&&
|
||||||
|
is_detected<key_type_t, T>::value >>
|
||||||
|
{
|
||||||
|
// maps with non-unique keys (std::multimap, std::unordered_multimap, ...)
|
||||||
|
// are excluded, because an object cannot hold duplicate keys; they are
|
||||||
|
// detected by insert() returning an iterator instead of a pair<iterator, bool>
|
||||||
|
// NOLINTNEXTLINE(modernize-type-traits) we use C++11
|
||||||
|
static constexpr bool value = std::is_enum<typename T::key_type>::value &&
|
||||||
|
!(is_detected<insert_result_t, T>::value && !is_detected<insert_result_second_t, T>::value);
|
||||||
|
};
|
||||||
|
|
||||||
template<typename BasicJsonType, typename ConstructibleObjectType,
|
template<typename BasicJsonType, typename ConstructibleObjectType,
|
||||||
typename = void>
|
typename = void>
|
||||||
struct is_constructible_object_type_impl : std::false_type {};
|
struct is_constructible_object_type_impl : std::false_type {};
|
||||||
@@ -6047,11 +6082,40 @@ auto from_json(BasicJsonType&& j, TupleRelated&& t)
|
|||||||
return from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {});
|
return from_json_tuple_impl(std::forward<BasicJsonType>(j), std::forward<TupleRelated>(t), priority_tag<3> {});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// read a map with enum keys from an object, using the enum's own from_json for
|
||||||
|
// the keys (e.g., from NLOHMANN_JSON_SERIALIZE_ENUM); this is the form written
|
||||||
|
// with JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
template<typename BasicJsonType, typename Map>
|
||||||
|
inline bool from_json_enum_keyed_object(const BasicJsonType& j, Map& m, std::true_type /*key is enum*/)
|
||||||
|
{
|
||||||
|
if (!j.is_object())
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
m.clear();
|
||||||
|
for (const auto& p : *j.template get_ptr<const typename BasicJsonType::object_t*>())
|
||||||
|
{
|
||||||
|
m.emplace(BasicJsonType(p.first).template get<typename Map::key_type>(), p.second.template get<typename Map::mapped_type>());
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename BasicJsonType, typename Map>
|
||||||
|
inline bool from_json_enum_keyed_object(const BasicJsonType& /*j*/, Map& /*m*/, std::false_type /*key is enum*/)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
|
template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
|
||||||
typename = enable_if_t < !std::is_constructible <
|
typename = enable_if_t < !std::is_constructible <
|
||||||
typename BasicJsonType::string_t, Key >::value >>
|
typename BasicJsonType::string_t, Key >::value >>
|
||||||
inline void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
|
inline void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
|
||||||
{
|
{
|
||||||
|
// NOLINTNEXTLINE(modernize-type-traits) we use C++11
|
||||||
|
if (from_json_enum_keyed_object(j, m, std::is_enum<Key> {}))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
||||||
{
|
{
|
||||||
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
||||||
@@ -6072,6 +6136,11 @@ template < typename BasicJsonType, typename Key, typename Value, typename Hash,
|
|||||||
typename BasicJsonType::string_t, Key >::value >>
|
typename BasicJsonType::string_t, Key >::value >>
|
||||||
inline void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
|
inline void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
|
||||||
{
|
{
|
||||||
|
// NOLINTNEXTLINE(modernize-type-traits) we use C++11
|
||||||
|
if (from_json_enum_keyed_object(j, m, std::is_enum<Key> {}))
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
||||||
{
|
{
|
||||||
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
||||||
@@ -6167,6 +6236,8 @@ NLOHMANN_JSON_NAMESPACE_END
|
|||||||
#include <valarray> // valarray
|
#include <valarray> // valarray
|
||||||
#include <vector> // vector
|
#include <vector> // vector
|
||||||
|
|
||||||
|
// #include <nlohmann/detail/exceptions.hpp>
|
||||||
|
|
||||||
// #include <nlohmann/detail/iterators/iteration_proxy.hpp>
|
// #include <nlohmann/detail/iterators/iteration_proxy.hpp>
|
||||||
// __ _____ _____ _____
|
// __ _____ _____ _____
|
||||||
// __| | __| | | | JSON for Modern C++
|
// __| | __| | | | JSON for Modern C++
|
||||||
@@ -6910,6 +6981,9 @@ template < typename BasicJsonType, typename CompatibleArrayType,
|
|||||||
!is_basic_json<CompatibleArrayType>::value
|
!is_basic_json<CompatibleArrayType>::value
|
||||||
#if JSON_HAS_RANGES && !defined(__MINGW32__)
|
#if JSON_HAS_RANGES && !defined(__MINGW32__)
|
||||||
&& !is_compatible_range_view<CompatibleArrayType>::value
|
&& !is_compatible_range_view<CompatibleArrayType>::value
|
||||||
|
#endif
|
||||||
|
#if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
&& !is_enum_keyed_map<CompatibleArrayType>::value
|
||||||
#endif
|
#endif
|
||||||
,
|
,
|
||||||
int > = 0 >
|
int > = 0 >
|
||||||
@@ -6964,6 +7038,33 @@ inline void to_json(BasicJsonType& j, const CompatibleObjectType& obj)
|
|||||||
external_constructor<value_t::object>::construct(j, obj);
|
external_constructor<value_t::object>::construct(j, obj);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
// store a map with enum keys as an object, using the enum's own to_json for the
|
||||||
|
// keys (e.g., from NLOHMANN_JSON_SERIALIZE_ENUM); without the macro, such maps
|
||||||
|
// are stored as arrays of [key, value] pairs
|
||||||
|
template < typename BasicJsonType, typename EnumKeyedMap,
|
||||||
|
enable_if_t < is_enum_keyed_map<EnumKeyedMap>::value&& !is_basic_json<EnumKeyedMap>::value, int > = 0 >
|
||||||
|
inline void to_json(BasicJsonType& j, const EnumKeyedMap& map)
|
||||||
|
{
|
||||||
|
typename BasicJsonType::object_t obj;
|
||||||
|
for (const auto& p : map)
|
||||||
|
{
|
||||||
|
BasicJsonType key = p.first;
|
||||||
|
if (JSON_HEDLEY_UNLIKELY(!key.is_string()))
|
||||||
|
{
|
||||||
|
JSON_THROW(type_error::create(302, concat("type must be string, but is ", key.type_name()), &key));
|
||||||
|
}
|
||||||
|
|
||||||
|
auto& key_string = *key.template get_ptr<typename BasicJsonType::string_t*>();
|
||||||
|
if (JSON_HEDLEY_UNLIKELY(!obj.emplace(key_string, BasicJsonType(p.second)).second))
|
||||||
|
{
|
||||||
|
JSON_THROW(type_error::create(318, concat("duplicate object key '", key_string, "'"), &key));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
external_constructor<value_t::object>::construct(j, std::move(obj));
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
template<typename BasicJsonType>
|
template<typename BasicJsonType>
|
||||||
inline void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
|
inline void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj)
|
||||||
{
|
{
|
||||||
@@ -32549,6 +32650,7 @@ struct formatter<nlohmann::NLOHMANN_BASIC_JSON_TPL, char> // NOLINT(cert-dcl58-c
|
|||||||
#undef JSON_BRACE_INIT_COPY_SEMANTICS
|
#undef JSON_BRACE_INIT_COPY_SEMANTICS
|
||||||
#undef JSON_PRECISE_STREAM_POSITION
|
#undef JSON_PRECISE_STREAM_POSITION
|
||||||
#undef JSON_STRICT_NUL_HANDLING
|
#undef JSON_STRICT_NUL_HANDLING
|
||||||
|
#undef JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
|
// #include <nlohmann/thirdparty/hedley/hedley_undef.hpp>
|
||||||
|
|||||||
@@ -64,6 +64,10 @@
|
|||||||
#define JSON_STRICT_NUL_HANDLING 0
|
#define JSON_STRICT_NUL_HANDLING 0
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#ifndef JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
#define JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS 0
|
||||||
|
#endif
|
||||||
|
|
||||||
#if JSON_DIAGNOSTICS
|
#if JSON_DIAGNOSTICS
|
||||||
#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag
|
#define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag
|
||||||
#else
|
#else
|
||||||
@@ -100,14 +104,20 @@
|
|||||||
#define NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING
|
#define NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
#define NLOHMANN_JSON_ABI_TAG_OBJECTS_FOR_ENUM_KEYED_MAPS _ekmo
|
||||||
|
#else
|
||||||
|
#define NLOHMANN_JSON_ABI_TAG_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
#endif
|
||||||
|
|
||||||
#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION
|
#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION
|
||||||
#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0
|
#define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
// Construct the namespace ABI tags component
|
// Construct the namespace ABI tags component
|
||||||
#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c, d, e, f) json_abi ## a ## b ## c ## d ## e ## f
|
#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c, d, e, f, g) json_abi ## a ## b ## c ## d ## e ## f ## g
|
||||||
#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b, c, d, e, f) \
|
#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b, c, d, e, f, g) \
|
||||||
NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c, d, e, f)
|
NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b, c, d, e, f, g)
|
||||||
|
|
||||||
#define NLOHMANN_JSON_ABI_TAGS \
|
#define NLOHMANN_JSON_ABI_TAGS \
|
||||||
NLOHMANN_JSON_ABI_TAGS_CONCAT( \
|
NLOHMANN_JSON_ABI_TAGS_CONCAT( \
|
||||||
@@ -116,7 +126,8 @@
|
|||||||
NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS, \
|
NLOHMANN_JSON_ABI_TAG_DIAGNOSTIC_POSITIONS, \
|
||||||
NLOHMANN_JSON_ABI_TAG_BRACE_INIT_COPY_SEMANTICS, \
|
NLOHMANN_JSON_ABI_TAG_BRACE_INIT_COPY_SEMANTICS, \
|
||||||
NLOHMANN_JSON_ABI_TAG_PRECISE_STREAM_POSITION, \
|
NLOHMANN_JSON_ABI_TAG_PRECISE_STREAM_POSITION, \
|
||||||
NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING)
|
NLOHMANN_JSON_ABI_TAG_STRICT_NUL_HANDLING, \
|
||||||
|
NLOHMANN_JSON_ABI_TAG_OBJECTS_FOR_ENUM_KEYED_MAPS)
|
||||||
|
|
||||||
// Construct the namespace version component
|
// Construct the namespace version component
|
||||||
#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \
|
#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \
|
||||||
|
|||||||
@@ -44,6 +44,10 @@ TEST_CASE("default namespace")
|
|||||||
expected += "_snul";
|
expected += "_snul";
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
expected += "_ekmo";
|
||||||
|
#endif
|
||||||
|
|
||||||
expected += "_v" STRINGIZE(NLOHMANN_JSON_VERSION_MAJOR);
|
expected += "_v" STRINGIZE(NLOHMANN_JSON_VERSION_MAJOR);
|
||||||
expected += "_" STRINGIZE(NLOHMANN_JSON_VERSION_MINOR);
|
expected += "_" STRINGIZE(NLOHMANN_JSON_VERSION_MINOR);
|
||||||
expected += "_" STRINGIZE(NLOHMANN_JSON_VERSION_PATCH) "::basic_json";
|
expected += "_" STRINGIZE(NLOHMANN_JSON_VERSION_PATCH) "::basic_json";
|
||||||
|
|||||||
@@ -45,6 +45,10 @@ TEST_CASE("default namespace without version component")
|
|||||||
expected += "_snul";
|
expected += "_snul";
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#if JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
expected += "_ekmo";
|
||||||
|
#endif
|
||||||
|
|
||||||
expected += "::basic_json";
|
expected += "::basic_json";
|
||||||
|
|
||||||
// fallback for Clang
|
// fallback for Clang
|
||||||
|
|||||||
@@ -0,0 +1,246 @@
|
|||||||
|
// __ _____ _____ _____
|
||||||
|
// __| | __| | | | JSON for Modern C++ (supporting code)
|
||||||
|
// | | |__ | | | | | | version 3.12.0
|
||||||
|
// |_____|_____|_____|_|___| https://github.com/nlohmann/json
|
||||||
|
//
|
||||||
|
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#include "doctest_compatibility.h"
|
||||||
|
|
||||||
|
// skip tests if JSON_DisableEnumSerialization=ON (#4384)
|
||||||
|
#if defined(JSON_DISABLE_ENUM_SERIALIZATION) && (JSON_DISABLE_ENUM_SERIALIZATION == 1)
|
||||||
|
#define SKIP_TESTS_FOR_ENUM_SERIALIZATION
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// This file tests the opt-in JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS, so it defines
|
||||||
|
// the macro itself rather than relying on a -D flag, and runs in every build.
|
||||||
|
// The default behavior is tested in unit-enum_keyed_maps_default.cpp.
|
||||||
|
#ifdef JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
#undef JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS 1
|
||||||
|
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
|
using nlohmann::json;
|
||||||
|
using nlohmann::ordered_json;
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <functional>
|
||||||
|
#include <map>
|
||||||
|
#include <string>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#define STRINGIZE_EX(x) #x
|
||||||
|
#define STRINGIZE(x) STRINGIZE_EX(x)
|
||||||
|
|
||||||
|
// NLOHMANN_JSON_SERIALIZE_ENUM uses a static std::pair
|
||||||
|
DOCTEST_CLANG_SUPPRESS_WARNING_PUSH
|
||||||
|
DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors")
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
// std::hash is only required for enums since C++14
|
||||||
|
struct enum_hash
|
||||||
|
{
|
||||||
|
template<typename T>
|
||||||
|
std::size_t operator()(T t) const noexcept
|
||||||
|
{
|
||||||
|
return static_cast<std::size_t>(t);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
// the example from #4378
|
||||||
|
enum TaskState // NOLINT(cert-int09-c,readability-enum-initial-value,cppcoreguidelines-use-enum-class)
|
||||||
|
{
|
||||||
|
TS_STOPPED,
|
||||||
|
TS_RUNNING,
|
||||||
|
TS_COMPLETED,
|
||||||
|
TS_INVALID = -1,
|
||||||
|
};
|
||||||
|
|
||||||
|
// NOLINTNEXTLINE(misc-const-correctness,misc-use-internal-linkage,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive
|
||||||
|
NLOHMANN_JSON_SERIALIZE_ENUM(TaskState,
|
||||||
|
{
|
||||||
|
{TS_INVALID, nullptr},
|
||||||
|
{TS_STOPPED, "stopped"},
|
||||||
|
{TS_RUNNING, "running"},
|
||||||
|
{TS_COMPLETED, "completed"},
|
||||||
|
})
|
||||||
|
|
||||||
|
enum class color {red, green, blue}; // blue is not mapped and falls back to "red"
|
||||||
|
|
||||||
|
// NOLINTNEXTLINE(misc-const-correctness,misc-use-internal-linkage,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive
|
||||||
|
NLOHMANN_JSON_SERIALIZE_ENUM(color,
|
||||||
|
{
|
||||||
|
{color::red, "red"},
|
||||||
|
{color::green, "green"},
|
||||||
|
})
|
||||||
|
|
||||||
|
enum class strict_color {red, green, blue}; // blue is not mapped
|
||||||
|
|
||||||
|
// NOLINTNEXTLINE(misc-const-correctness,misc-use-internal-linkage,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive
|
||||||
|
NLOHMANN_JSON_SERIALIZE_ENUM_STRICT(strict_color,
|
||||||
|
{
|
||||||
|
{strict_color::red, "red"},
|
||||||
|
{strict_color::green, "green"},
|
||||||
|
})
|
||||||
|
|
||||||
|
enum class digit {zero, one};
|
||||||
|
|
||||||
|
// NOLINTNEXTLINE(misc-const-correctness,misc-use-internal-linkage,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive
|
||||||
|
NLOHMANN_JSON_SERIALIZE_ENUM(digit,
|
||||||
|
{
|
||||||
|
{digit::zero, 0},
|
||||||
|
{digit::one, 1},
|
||||||
|
})
|
||||||
|
|
||||||
|
#ifndef SKIP_TESTS_FOR_ENUM_SERIALIZATION
|
||||||
|
enum class plain {zero, one}; // serialized as integer
|
||||||
|
#endif
|
||||||
|
|
||||||
|
TEST_CASE("JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS")
|
||||||
|
{
|
||||||
|
SECTION("the macro is part of the ABI tag")
|
||||||
|
{
|
||||||
|
const std::string ns = STRINGIZE(NLOHMANN_JSON_NAMESPACE);
|
||||||
|
CHECK(ns.find("_ekmo") != std::string::npos);
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("std::map (#4378)")
|
||||||
|
{
|
||||||
|
using task_map = std::map<TaskState, std::string>;
|
||||||
|
const task_map m = {{TS_STOPPED, "aa"}, {TS_COMPLETED, "bb"}};
|
||||||
|
const json j = m;
|
||||||
|
CHECK(j == json::parse(R"({"stopped":"aa","completed":"bb"})"));
|
||||||
|
CHECK(j.get<task_map>() == m);
|
||||||
|
|
||||||
|
json j2;
|
||||||
|
j2["x"] = m;
|
||||||
|
CHECK(j2.dump() == R"({"x":{"completed":"bb","stopped":"aa"}})");
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("std::map with custom comparator")
|
||||||
|
{
|
||||||
|
using task_map = std::map<TaskState, int, std::greater<TaskState>>;
|
||||||
|
const task_map m = {{TS_STOPPED, 1}, {TS_RUNNING, 2}};
|
||||||
|
const json j = m;
|
||||||
|
CHECK(j == json::parse(R"({"stopped":1,"running":2})"));
|
||||||
|
CHECK(j.get<task_map>() == m);
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("std::unordered_map")
|
||||||
|
{
|
||||||
|
using task_map = std::unordered_map<TaskState, int, enum_hash>;
|
||||||
|
const task_map m = {{TS_STOPPED, 1}, {TS_RUNNING, 2}};
|
||||||
|
const json j = m;
|
||||||
|
CHECK(j == json::parse(R"({"stopped":1,"running":2})"));
|
||||||
|
CHECK(j.get<task_map>() == m);
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("nested maps")
|
||||||
|
{
|
||||||
|
using nested_map = std::map<color, std::map<TaskState, int>>;
|
||||||
|
const nested_map m = {{color::green, {{TS_RUNNING, 1}}}, {color::red, {}}};
|
||||||
|
const json j = m;
|
||||||
|
CHECK(j == json::parse(R"({"green":{"running":1},"red":{}})"));
|
||||||
|
CHECK(j.get<nested_map>() == m);
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("ordered_json keeps the order of the map")
|
||||||
|
{
|
||||||
|
using task_map = std::map<TaskState, int>;
|
||||||
|
const task_map m = {{TS_STOPPED, 1}, {TS_RUNNING, 2}, {TS_COMPLETED, 3}};
|
||||||
|
const ordered_json j = m;
|
||||||
|
CHECK(j.dump() == R"({"stopped":1,"running":2,"completed":3})");
|
||||||
|
CHECK(j.get<task_map>() == m);
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("empty map")
|
||||||
|
{
|
||||||
|
const json j = std::map<TaskState, int>();
|
||||||
|
CHECK(j.is_object());
|
||||||
|
CHECK(j.empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("NLOHMANN_JSON_SERIALIZE_ENUM_STRICT")
|
||||||
|
{
|
||||||
|
using color_map = std::map<strict_color, int>;
|
||||||
|
const color_map m = {{strict_color::red, 1}, {strict_color::green, 2}};
|
||||||
|
const json j = m;
|
||||||
|
CHECK(j == json::parse(R"({"red":1,"green":2})"));
|
||||||
|
CHECK(j.get<color_map>() == m);
|
||||||
|
|
||||||
|
const color_map unmapped = {{strict_color::blue, 1}};
|
||||||
|
json _;
|
||||||
|
CHECK_THROWS_WITH_AS(_ = unmapped,
|
||||||
|
"[json.exception.out_of_range.410] enum value out of range for strict_color", json::out_of_range&);
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("arrays of [key, value] pairs are still read")
|
||||||
|
{
|
||||||
|
using task_map = std::map<TaskState, int>;
|
||||||
|
const task_map m = {{TS_STOPPED, 1}};
|
||||||
|
CHECK(json::parse(R"([["stopped",1]])").get<task_map>() == m);
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("other containers are not affected")
|
||||||
|
{
|
||||||
|
const std::vector<std::pair<TaskState, int>> pairs = {{TS_STOPPED, 1}};
|
||||||
|
const std::map<std::string, TaskState> string_keys = {{"a", TS_STOPPED}};
|
||||||
|
const std::map<int, int> int_keys = {{1, 2}};
|
||||||
|
CHECK(json(pairs) == json::parse(R"([["stopped",1]])"));
|
||||||
|
CHECK(json(string_keys) == json::parse(R"({"a":"stopped"})"));
|
||||||
|
CHECK(json(int_keys) == json::parse("[[1,2]]"));
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("maps with non-unique keys are still stored as arrays of pairs")
|
||||||
|
{
|
||||||
|
const std::multimap<TaskState, int> mm = {{TS_STOPPED, 1}, {TS_STOPPED, 2}};
|
||||||
|
const std::unordered_multimap<TaskState, int, enum_hash> umm = {{TS_RUNNING, 3}, {TS_RUNNING, 3}};
|
||||||
|
CHECK(json(mm) == json::parse(R"([["stopped",1],["stopped",2]])"));
|
||||||
|
CHECK(json(umm) == json::parse(R"([["running",3],["running",3]])"));
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("keys that do not serialize to strings")
|
||||||
|
{
|
||||||
|
const std::map<TaskState, int> null_key = {{TS_INVALID, 1}};
|
||||||
|
const std::map<digit, int> number_key = {{digit::zero, 1}};
|
||||||
|
json j = "unchanged";
|
||||||
|
|
||||||
|
// mapped to null
|
||||||
|
CHECK_THROWS_WITH_AS(j = null_key,
|
||||||
|
"[json.exception.type_error.302] type must be string, but is null", json::type_error&);
|
||||||
|
|
||||||
|
// mapped to a number
|
||||||
|
CHECK_THROWS_WITH_AS(j = number_key,
|
||||||
|
"[json.exception.type_error.302] type must be string, but is number", json::type_error&);
|
||||||
|
|
||||||
|
#ifndef SKIP_TESTS_FOR_ENUM_SERIALIZATION
|
||||||
|
// enum without NLOHMANN_JSON_SERIALIZE_ENUM
|
||||||
|
const std::map<plain, int> plain_key = {{plain::zero, 1}};
|
||||||
|
CHECK_THROWS_WITH_AS(j = plain_key,
|
||||||
|
"[json.exception.type_error.302] type must be string, but is number", json::type_error&);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
CHECK(j == "unchanged");
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("keys that serialize to the same string")
|
||||||
|
{
|
||||||
|
const std::map<color, int> m = {{color::red, 1}, {color::blue, 2}};
|
||||||
|
json j = "unchanged";
|
||||||
|
|
||||||
|
// color::blue is not mapped and falls back to "red"
|
||||||
|
CHECK_THROWS_WITH_AS(j = m,
|
||||||
|
"[json.exception.type_error.318] duplicate object key 'red'", json::type_error&);
|
||||||
|
|
||||||
|
CHECK(j == "unchanged");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
// __ _____ _____ _____
|
||||||
|
// __| | __| | | | JSON for Modern C++ (supporting code)
|
||||||
|
// | | |__ | | | | | | version 3.12.0
|
||||||
|
// |_____|_____|_____|_|___| https://github.com/nlohmann/json
|
||||||
|
//
|
||||||
|
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
#include "doctest_compatibility.h"
|
||||||
|
|
||||||
|
// This file tests maps with enum keys with the default setting of
|
||||||
|
// JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS (or whatever a -D flag sets it to).
|
||||||
|
// unit-enum_keyed_maps.cpp tests JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS=1.
|
||||||
|
// These tests are not part of unit-conversions.cpp, because that object file
|
||||||
|
// is already too big for the MinGW linker of some compilers.
|
||||||
|
|
||||||
|
#include <nlohmann/json.hpp>
|
||||||
|
using nlohmann::json;
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <functional>
|
||||||
|
#include <map>
|
||||||
|
#include <string>
|
||||||
|
#include <unordered_map>
|
||||||
|
|
||||||
|
// NLOHMANN_JSON_SERIALIZE_ENUM uses a static std::pair
|
||||||
|
DOCTEST_CLANG_SUPPRESS_WARNING_PUSH
|
||||||
|
DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors")
|
||||||
|
|
||||||
|
enum class cards {kreuz, pik, herz, karo};
|
||||||
|
|
||||||
|
// NOLINTNEXTLINE(misc-use-internal-linkage,misc-const-correctness,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive
|
||||||
|
NLOHMANN_JSON_SERIALIZE_ENUM(cards,
|
||||||
|
{
|
||||||
|
{cards::kreuz, "kreuz"},
|
||||||
|
{cards::pik, "pik"},
|
||||||
|
{cards::herz, "herz"},
|
||||||
|
{cards::karo, "karo"}
|
||||||
|
})
|
||||||
|
|
||||||
|
enum TaskState // NOLINT(cert-int09-c,readability-enum-initial-value,cppcoreguidelines-use-enum-class)
|
||||||
|
{
|
||||||
|
TS_STOPPED,
|
||||||
|
TS_RUNNING,
|
||||||
|
TS_COMPLETED,
|
||||||
|
TS_INVALID = -1,
|
||||||
|
};
|
||||||
|
|
||||||
|
// NOLINTNEXTLINE(misc-const-correctness,misc-use-internal-linkage,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive
|
||||||
|
NLOHMANN_JSON_SERIALIZE_ENUM(TaskState,
|
||||||
|
{
|
||||||
|
{TS_INVALID, nullptr},
|
||||||
|
{TS_STOPPED, "stopped"},
|
||||||
|
{TS_RUNNING, "running"},
|
||||||
|
{TS_COMPLETED, "completed"},
|
||||||
|
})
|
||||||
|
|
||||||
|
enum class strict_cards {kreuz, pik, herz, karo, andere}; // andere not included in mapping
|
||||||
|
|
||||||
|
// NOLINTNEXTLINE(misc-use-internal-linkage,misc-const-correctness,cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - false positive
|
||||||
|
NLOHMANN_JSON_SERIALIZE_ENUM_STRICT(strict_cards,
|
||||||
|
{
|
||||||
|
{strict_cards::kreuz, "kreuz"},
|
||||||
|
{strict_cards::pik, "pik"},
|
||||||
|
{strict_cards::herz, "herz"},
|
||||||
|
{strict_cards::karo, "karo"}
|
||||||
|
})
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
// std::hash is only required for enums since C++14
|
||||||
|
struct enum_hash
|
||||||
|
{
|
||||||
|
template<typename T>
|
||||||
|
std::size_t operator()(T t) const noexcept
|
||||||
|
{
|
||||||
|
return static_cast<std::size_t>(t);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
// see unit-enum_keyed_maps.cpp for JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS=1
|
||||||
|
TEST_CASE("maps with enum keys")
|
||||||
|
{
|
||||||
|
using task_map = std::map<TaskState, std::string>;
|
||||||
|
using task_umap = std::unordered_map<TaskState, std::string, enum_hash>;
|
||||||
|
using task_gmap = std::map<TaskState, std::string, std::greater<TaskState>>;
|
||||||
|
using nested_map = std::map<cards, std::map<TaskState, int>>;
|
||||||
|
using strict_map = std::map<strict_cards, int>;
|
||||||
|
using int_map = std::map<int, int>;
|
||||||
|
using int_umap = std::unordered_map<int, int>;
|
||||||
|
|
||||||
|
const task_map m = {{TS_STOPPED, "aa"}, {TS_COMPLETED, "bb"}};
|
||||||
|
|
||||||
|
#if !JSON_USE_OBJECTS_FOR_ENUM_KEYED_MAPS
|
||||||
|
SECTION("stored as array of pairs")
|
||||||
|
{
|
||||||
|
CHECK(json(m) == json::parse(R"([["stopped","aa"],["completed","bb"]])"));
|
||||||
|
CHECK(json(task_umap {{TS_RUNNING, "cc"}}) == json::parse(R"([["running","cc"]])"));
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
SECTION("read from array of pairs")
|
||||||
|
{
|
||||||
|
CHECK(json::parse(R"([["stopped","aa"],["completed","bb"]])").get<task_map>() == m);
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("read from object (#4378)")
|
||||||
|
{
|
||||||
|
const json j = json::parse(R"({"stopped":"aa","completed":"bb"})");
|
||||||
|
CHECK(j.get<task_map>() == m);
|
||||||
|
CHECK(j.get<task_umap>() == task_umap(m.begin(), m.end()));
|
||||||
|
CHECK(j.get<task_gmap>() == task_gmap(m.begin(), m.end()));
|
||||||
|
CHECK(json::parse(R"({"kreuz":{"stopped":1}})").get<nested_map>() == nested_map {{cards::kreuz, {{TS_STOPPED, 1}}}});
|
||||||
|
CHECK(nlohmann::ordered_json::parse(R"({"stopped":"aa","completed":"bb"})").get<task_map>() == m);
|
||||||
|
|
||||||
|
// object keys go through the enum's from_json
|
||||||
|
strict_map sm;
|
||||||
|
CHECK_THROWS_WITH_AS(json::parse(R"({"what?":1})").get_to(sm),
|
||||||
|
"[json.exception.out_of_range.410] enum value out of range for strict_cards: \"what?\"", json::out_of_range&);
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("objects are only read for enum keys")
|
||||||
|
{
|
||||||
|
int_map im;
|
||||||
|
int_umap ium;
|
||||||
|
CHECK_THROWS_WITH_AS(json::parse(R"({"1":2})").get_to(im),
|
||||||
|
"[json.exception.type_error.302] type must be array, but is object", json::type_error&);
|
||||||
|
CHECK_THROWS_WITH_AS(json::parse(R"({"1":2})").get_to(ium),
|
||||||
|
"[json.exception.type_error.302] type must be array, but is object", json::type_error&);
|
||||||
|
}
|
||||||
|
|
||||||
|
SECTION("other types are rejected")
|
||||||
|
{
|
||||||
|
task_map tm;
|
||||||
|
CHECK_THROWS_WITH_AS(json("stopped").get_to(tm),
|
||||||
|
"[json.exception.type_error.302] type must be array, but is string", json::type_error&);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
DOCTEST_CLANG_SUPPRESS_WARNING_POP
|
||||||
@@ -20,7 +20,7 @@ if __name__ == '__main__':
|
|||||||
|
|
||||||
namespaces = ['nlohmann']
|
namespaces = ['nlohmann']
|
||||||
abi_prefix = 'json_abi'
|
abi_prefix = 'json_abi'
|
||||||
abi_tags = ['_diag', '_ldvcmp', '_dp', '_bics', '_psp', '_snul']
|
abi_tags = ['_diag', '_ldvcmp', '_dp', '_bics', '_psp', '_snul', '_ekmo']
|
||||||
version = '_v' + args.version.replace('.', '_')
|
version = '_v' + args.version.replace('.', '_')
|
||||||
inline_namespaces = []
|
inline_namespaces = []
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user