Merge branch 'develop' of https://github.com/nlohmann/json into new_ci_images

This commit is contained in:
Niels Lohmann 2022-06-03 10:11:32 +02:00
commit e8d57c2c3d
No known key found for this signature in database
GPG Key ID: 7F3CEA63AE251B69
132 changed files with 4221 additions and 1104 deletions

View File

@ -48,7 +48,7 @@ jobs:
container: ghcr.io/nlohmann/json-ci:v2.3.0 container: ghcr.io/nlohmann/json-ci:v2.3.0
strategy: strategy:
matrix: matrix:
target: [ci_test_diagnostics, ci_test_noexceptions, ci_test_noimplicitconversions] target: [ci_test_diagnostics, ci_test_noexceptions, ci_test_noimplicitconversions, ci_test_legacycomparison]
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- name: cmake - name: cmake

View File

@ -37,13 +37,14 @@ if(${MAIN_PROJECT} AND (${CMAKE_VERSION} VERSION_EQUAL 3.13 OR ${CMAKE_VERSION}
else() else()
set(JSON_BuildTests_INIT OFF) set(JSON_BuildTests_INIT OFF)
endif() endif()
option(JSON_BuildTests "Build the unit tests when BUILD_TESTING is enabled." ${JSON_BuildTests_INIT}) option(JSON_BuildTests "Build the unit tests when BUILD_TESTING is enabled." ${JSON_BuildTests_INIT})
option(JSON_CI "Enable CI build targets." OFF) option(JSON_CI "Enable CI build targets." OFF)
option(JSON_Diagnostics "Use extended diagnostic messages." OFF) option(JSON_Diagnostics "Use extended diagnostic messages." OFF)
option(JSON_ImplicitConversions "Enable implicit conversions." ON) option(JSON_ImplicitConversions "Enable implicit conversions." ON)
option(JSON_Install "Install CMake targets during install step." ${MAIN_PROJECT}) option(JSON_LegacyDiscardedValueComparison "Enable legacy discarded value comparison." OFF)
option(JSON_MultipleHeaders "Use non-amalgamated version of the library." OFF) option(JSON_Install "Install CMake targets during install step." ${MAIN_PROJECT})
option(JSON_SystemInclude "Include as system headers (skip for clang-tidy)." OFF) option(JSON_MultipleHeaders "Use non-amalgamated version of the library." OFF)
option(JSON_SystemInclude "Include as system headers (skip for clang-tidy)." OFF)
if (JSON_CI) if (JSON_CI)
include(ci) include(ci)
@ -77,6 +78,10 @@ if (NOT JSON_ImplicitConversions)
message(STATUS "Implicit conversions are disabled") message(STATUS "Implicit conversions are disabled")
endif() endif()
if (JSON_LegacyDiscardedValueComparison)
message(STATUS "Legacy discarded value comparison enabled")
endif()
if (JSON_Diagnostics) if (JSON_Diagnostics)
message(STATUS "Diagnostics enabled") message(STATUS "Diagnostics enabled")
endif() endif()
@ -100,8 +105,9 @@ endif()
target_compile_definitions( target_compile_definitions(
${NLOHMANN_JSON_TARGET_NAME} ${NLOHMANN_JSON_TARGET_NAME}
INTERFACE INTERFACE
JSON_USE_IMPLICIT_CONVERSIONS=$<BOOL:${JSON_ImplicitConversions}> $<$<NOT:$<BOOL:${JSON_ImplicitConversions}>>:JSON_USE_IMPLICIT_CONVERSIONS=0>
JSON_DIAGNOSTICS=$<BOOL:${JSON_Diagnostics}> $<$<BOOL:${JSON_Diagnostics}>:JSON_DIAGNOSTICS=1>
$<$<BOOL:${JSON_LegacyDiscardedValueComparison}>:JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON=1>
) )
target_include_directories( target_include_directories(

View File

@ -54,7 +54,7 @@ There are myriads of [JSON](https://json.org) libraries out there, and each may
- **Trivial integration**. Our whole code consists of a single header file [`json.hpp`](https://github.com/nlohmann/json/blob/develop/single_include/nlohmann/json.hpp). That's it. No library, no subproject, no dependencies, no complex build system. The class is written in vanilla C++11. All in all, everything should require no adjustment of your compiler flags or project settings. - **Trivial integration**. Our whole code consists of a single header file [`json.hpp`](https://github.com/nlohmann/json/blob/develop/single_include/nlohmann/json.hpp). That's it. No library, no subproject, no dependencies, no complex build system. The class is written in vanilla C++11. All in all, everything should require no adjustment of your compiler flags or project settings.
- **Serious testing**. Our class is heavily [unit-tested](https://github.com/nlohmann/json/tree/develop/tests/src) and covers [100%](https://coveralls.io/r/nlohmann/json) of the code, including all exceptional behavior. Furthermore, we checked with [Valgrind](https://valgrind.org) and the [Clang Sanitizers](https://clang.llvm.org/docs/index.html) that there are no memory leaks. [Google OSS-Fuzz](https://github.com/google/oss-fuzz/tree/master/projects/json) additionally runs fuzz tests against all parsers 24/7, effectively executing billions of tests so far. To maintain high quality, the project is following the [Core Infrastructure Initiative (CII) best practices](https://bestpractices.coreinfrastructure.org/projects/289). - **Serious testing**. Our code is heavily [unit-tested](https://github.com/nlohmann/json/tree/develop/tests/src) and covers [100%](https://coveralls.io/r/nlohmann/json) of the code, including all exceptional behavior. Furthermore, we checked with [Valgrind](https://valgrind.org) and the [Clang Sanitizers](https://clang.llvm.org/docs/index.html) that there are no memory leaks. [Google OSS-Fuzz](https://github.com/google/oss-fuzz/tree/master/projects/json) additionally runs fuzz tests against all parsers 24/7, effectively executing billions of tests so far. To maintain high quality, the project is following the [Core Infrastructure Initiative (CII) best practices](https://bestpractices.coreinfrastructure.org/projects/289).
Other aspects were not so important to us: Other aspects were not so important to us:
@ -69,6 +69,10 @@ See the [contribution guidelines](https://github.com/nlohmann/json/blob/master/.
You can sponsor this library at [GitHub Sponsors](https://github.com/sponsors/nlohmann). You can sponsor this library at [GitHub Sponsors](https://github.com/sponsors/nlohmann).
### :office: Corporate Sponsor
[![](https://upload.wikimedia.org/wikipedia/commons/thumb/9/9e/Codacy-logo-black.svg/320px-Codacy-logo-black.svg.png)](https://github.com/codacy)
### :label: Named Sponsors ### :label: Named Sponsors
- [Michael Hartmann](https://github.com/reFX-Mike) - [Michael Hartmann](https://github.com/reFX-Mike)
@ -1599,6 +1603,20 @@ I deeply appreciate the help of the following people.
- [Dirk Stolle](https://github.com/striezel) fixed typos in documentation. - [Dirk Stolle](https://github.com/striezel) fixed typos in documentation.
- [Daniel Albuschat](https://github.com/daniel-kun) corrected the parameter name in the `parse` documentation. - [Daniel Albuschat](https://github.com/daniel-kun) corrected the parameter name in the `parse` documentation.
- [Prince Mendiratta](https://github.com/Prince-Mendiratta) fixed a link to the FAQ. - [Prince Mendiratta](https://github.com/Prince-Mendiratta) fixed a link to the FAQ.
- [Florian Albrechtskirchinger](https://github.com/falbrechtskirchinger) implemented `std::string_view` support for object keys and made dozens of other improvements.
- [Qianqian Fang](https://github.com/fangq) implemented the Binary JData (BJData) format.
- [pketelsen](https://github.com/pketelsen) added macros `NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT` and `NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT`.
- [DarkZeros](https://github.com/DarkZeros) adjusted to code to not clash with Arduino defines.
- [flagarde](https://github.com/flagarde) fixed the output of `meta()` for MSVC.
- [Giovanni Cerretani](https://github.com/gcerretani) fixed a check for `std::filesystem`.
- [Dimitris Apostolou](https://github.com/rex4539) fixed a typo.
- [Ferry Huberts](https://github.com/fhuberts) fixed a typo.
- [Michael Nosthoff](https://github.com/heinemml) fixed a typo.
- [JungHoon Lee](https://github.com/jhnlee) fixed a typo.
- [Faruk D.](https://github.com/fdiblen) fixed the CITATION.CFF file.
- [Andrea Cocito](https://github.com/puffetto) added a clarification on macro usage to the documentation.
- [Krzysiek Karbowiak](https://github.com/kkarbowiak) refactored the tests to use `CHECK_THROWS_WITH_AS`.
- [Chaoqi Zhang](https://github.com/prncoprs) fixed a typo.
Thanks a lot for helping out! Please [let me know](mailto:mail@nlohmann.me) if I forgot someone. Thanks a lot for helping out! Please [let me know](mailto:mail@nlohmann.me) if I forgot someone.
@ -1613,7 +1631,7 @@ The library itself consists of a single header file licensed under the MIT licen
- [**Artistic Style**](http://astyle.sourceforge.net) for automatic source code indentation - [**Artistic Style**](http://astyle.sourceforge.net) for automatic source code indentation
- [**Clang**](https://clang.llvm.org) for compilation with code sanitizers - [**Clang**](https://clang.llvm.org) for compilation with code sanitizers
- [**CMake**](https://cmake.org) for build automation - [**CMake**](https://cmake.org) for build automation
- [**Codacity**](https://www.codacy.com) for further [code analysis](https://www.codacy.com/app/nlohmann/json) - [**Codacy**](https://www.codacy.com) for further [code analysis](https://www.codacy.com/app/nlohmann/json)
- [**Coveralls**](https://coveralls.io) to measure [code coverage](https://coveralls.io/github/nlohmann/json) - [**Coveralls**](https://coveralls.io) to measure [code coverage](https://coveralls.io/github/nlohmann/json)
- [**Coverity Scan**](https://scan.coverity.com) for [static analysis](https://scan.coverity.com/projects/nlohmann-json) - [**Coverity Scan**](https://scan.coverity.com) for [static analysis](https://scan.coverity.com/projects/nlohmann-json)
- [**cppcheck**](http://cppcheck.sourceforge.net) for static analysis - [**cppcheck**](http://cppcheck.sourceforge.net) for static analysis

View File

@ -498,6 +498,20 @@ add_custom_target(ci_test_diagnostics
COMMENT "Compile and test with improved diagnostics enabled" COMMENT "Compile and test with improved diagnostics enabled"
) )
###############################################################################
# Enable legacy discarded value comparison.
###############################################################################
add_custom_target(ci_test_legacycomparison
COMMAND CXX=${CLANG_TOOL} ${CMAKE_COMMAND}
-DCMAKE_BUILD_TYPE=Debug -GNinja
-DJSON_BuildTests=ON -DJSON_MultipleHeaders=ON -DJSON_LegacyDiscardedValueComparison=ON
-S${PROJECT_SOURCE_DIR} -B${PROJECT_BINARY_DIR}/build_legacycomparison
COMMAND ${CMAKE_COMMAND} --build ${PROJECT_BINARY_DIR}/build_legacycomparison
COMMAND cd ${PROJECT_BINARY_DIR}/build_legacycomparison && ${CMAKE_CTEST_COMMAND} --parallel ${N} --output-on-failure
COMMENT "Compile and test with legacy discarded value comparison enabled"
)
############################################################################### ###############################################################################
# Coverage. # Coverage.
############################################################################### ###############################################################################
@ -797,8 +811,9 @@ endfunction()
ci_get_cmake(3.1.0 CMAKE_3_1_0_BINARY) ci_get_cmake(3.1.0 CMAKE_3_1_0_BINARY)
ci_get_cmake(3.13.0 CMAKE_3_13_0_BINARY) ci_get_cmake(3.13.0 CMAKE_3_13_0_BINARY)
set(JSON_CMAKE_FLAGS_3_1_0 "JSON_Install;JSON_MultipleHeaders;JSON_ImplicitConversions;JSON_Valgrind;JSON_Diagnostics;JSON_SystemInclude") set(JSON_CMAKE_FLAGS_3_1_0 JSON_Diagnostics JSON_ImplicitConversions JSON_LegacyDiscardedValueComparison
set(JSON_CMAKE_FLAGS_3_13_0 "JSON_BuildTests") JSON_Install JSON_MultipleHeaders JSON_SystemInclude JSON_Valgrind)
set(JSON_CMAKE_FLAGS_3_13_0 JSON_BuildTests)
function(ci_add_cmake_flags_targets flag min_version) function(ci_add_cmake_flags_targets flag min_version)
string(TOLOWER "ci_cmake_flag_${flag}" flag_target) string(TOLOWER "ci_cmake_flag_${flag}" flag_target)

View File

@ -156,6 +156,7 @@ endfunction()
############################################################################# #############################################################################
# json_test_add_test_for( # json_test_add_test_for(
# <file> # <file>
# [NAME <name>]
# MAIN <main> # MAIN <main>
# [CXX_STANDARDS <version_number>...] [FORCE]) # [CXX_STANDARDS <version_number>...] [FORCE])
# #
@ -165,6 +166,7 @@ endfunction()
# #
# if C++ standard <version_number> is supported by the compiler and the # if C++ standard <version_number> is supported by the compiler and the
# source file contains JSON_HAS_CPP_<version_number>. # source file contains JSON_HAS_CPP_<version_number>.
# Use NAME <name> to override the filename-derived test name.
# Use FORCE to create the test regardless of the file containing # Use FORCE to create the test regardless of the file containing
# JSON_HAS_CPP_<version_number>. # JSON_HAS_CPP_<version_number>.
# Test targets are linked against <main>. # Test targets are linked against <main>.
@ -172,15 +174,22 @@ endfunction()
############################################################################# #############################################################################
function(json_test_add_test_for file) function(json_test_add_test_for file)
cmake_parse_arguments(args "FORCE" "MAIN" "CXX_STANDARDS" ${ARGN}) cmake_parse_arguments(args "FORCE" "MAIN;NAME" "CXX_STANDARDS" ${ARGN})
get_filename_component(file_basename ${file} NAME_WE)
string(REGEX REPLACE "unit-([^$]+)" "test-\\1" test_name ${file_basename})
if("${args_MAIN}" STREQUAL "") if("${args_MAIN}" STREQUAL "")
message(FATAL_ERROR "Required argument MAIN <main> missing.") message(FATAL_ERROR "Required argument MAIN <main> missing.")
endif() endif()
if("${args_NAME}" STREQUAL "")
get_filename_component(file_basename ${file} NAME_WE)
string(REGEX REPLACE "unit-([^$]+)" "test-\\1" test_name ${file_basename})
else()
set(test_name ${args_NAME})
if(NOT test_name MATCHES "test-[^$]+")
message(FATAL_ERROR "Test name must start with 'test-'.")
endif()
endif()
if("${args_CXX_STANDARDS}" STREQUAL "") if("${args_CXX_STANDARDS}" STREQUAL "")
set(args_CXX_STANDARDS 11) set(args_CXX_STANDARDS 11)
endif() endif()

View File

@ -0,0 +1,23 @@
#include <iostream>
#include <nlohmann/json.hpp>
// define a byte container based on std::vector
using byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;
using json = nlohmann::json;
int main()
{
// (1) create empty container
auto c1 = byte_container_with_subtype();
std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};
// (2) create container
auto c2 = byte_container_with_subtype(bytes);
// (3) create container with subtype
auto c3 = byte_container_with_subtype(bytes, 42);
std::cout << json(c1) << "\n" << json(c2) << "\n" << json(c3) << std::endl;
}

View File

@ -0,0 +1,3 @@
{"bytes":[],"subtype":null}
{"bytes":[202,254,186,190],"subtype":null}
{"bytes":[202,254,186,190],"subtype":42}

View File

@ -0,0 +1,21 @@
#include <iostream>
#include <nlohmann/json.hpp>
// define a byte container based on std::vector
using byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;
using json = nlohmann::json;
int main()
{
std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};
// create container with subtype
auto c1 = byte_container_with_subtype(bytes, 42);
std::cout << "before calling clear_subtype(): " << json(c1) << '\n';
c1.clear_subtype();
std::cout << "after calling clear_subtype(): " << json(c1) << '\n';
}

View File

@ -0,0 +1,2 @@
before calling clear_subtype(): {"bytes":[202,254,186,190],"subtype":42}
after calling clear_subtype(): {"bytes":[202,254,186,190],"subtype":null}

View File

@ -0,0 +1,19 @@
#include <iostream>
#include <nlohmann/json.hpp>
// define a byte container based on std::vector
using byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;
int main()
{
std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};
// create container
auto c1 = byte_container_with_subtype(bytes);
// create container with subtype
auto c2 = byte_container_with_subtype(bytes, 42);
std::cout << std::boolalpha << "c1.has_subtype() = " << c1.has_subtype()
<< "\nc2.has_subtype() = " << c2.has_subtype() << std::endl;
}

View File

@ -0,0 +1,2 @@
c1.has_subtype() = false
c2.has_subtype() = true

View File

@ -0,0 +1,22 @@
#include <iostream>
#include <nlohmann/json.hpp>
// define a byte container based on std::vector
using byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;
using json = nlohmann::json;
int main()
{
std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};
// create container without subtype
auto c = byte_container_with_subtype(bytes);
std::cout << "before calling set_subtype(42): " << json(c) << '\n';
// set the subtype
c.set_subtype(42);
std::cout << "after calling set_subtype(42): " << json(c) << '\n';
}

View File

@ -0,0 +1,2 @@
before calling set_subtype(42): {"bytes":[202,254,186,190],"subtype":null}
after calling set_subtype(42): {"bytes":[202,254,186,190],"subtype":42}

View File

@ -0,0 +1,22 @@
#include <iostream>
#include <nlohmann/json.hpp>
// define a byte container based on std::vector
using byte_container_with_subtype = nlohmann::byte_container_with_subtype<std::vector<std::uint8_t>>;
int main()
{
std::vector<std::uint8_t> bytes = {{0xca, 0xfe, 0xba, 0xbe}};
// create container
auto c1 = byte_container_with_subtype(bytes);
// create container with subtype
auto c2 = byte_container_with_subtype(bytes, 42);
std::cout << "c1.subtype() = " << c1.subtype()
<< "\nc2.subtype() = " << c2.subtype() << std::endl;
// in case no subtype is set, return special value
assert(c1.subtype() == static_cast<byte_container_with_subtype::subtype_type>(-1));
}

View File

@ -0,0 +1,2 @@
c1.subtype() = 18446744073709551615
c2.subtype() = 42

View File

@ -0,0 +1,28 @@
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// tagged byte string
std::vector<std::uint8_t> vec = {{0xd8, 0x42, 0x44, 0xcA, 0xfe, 0xba, 0xbe}};
// cbor_tag_handler_t::error throws
try
{
auto b_throw_on_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::error);
}
catch (json::parse_error& e)
{
std::cout << e.what() << std::endl;
}
// cbor_tag_handler_t::ignore ignores the tag
auto b_ignore_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::ignore);
std::cout << b_ignore_tag << std::endl;
// cbor_tag_handler_t::store stores the tag as binary subtype
auto b_store_tag = json::from_cbor(vec, true, true, json::cbor_tag_handler_t::store);
std::cout << b_store_tag << std::endl;
}

View File

@ -0,0 +1,3 @@
[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0xD8
{"bytes":[202,254,186,190],"subtype":null}
{"bytes":[202,254,186,190],"subtype":66}

View File

@ -0,0 +1,11 @@
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
std::cout << std::boolalpha
<< "one < two : " << json::default_object_comparator_t{}("one", "two") << "\n"
<< "three < four : " << json::default_object_comparator_t{}("three", "four") << std::endl;
}

View File

@ -0,0 +1,2 @@
one < two : true
three < four : false

View File

@ -0,0 +1,24 @@
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON value with invalid UTF-8 byte sequence
json j_invalid = "ä\xA9ü";
try
{
std::cout << j_invalid.dump() << std::endl;
}
catch (json::type_error& e)
{
std::cout << e.what() << std::endl;
}
std::cout << "string with replaced invalid characters: "
<< j_invalid.dump(-1, ' ', false, json::error_handler_t::replace)
<< "\nstring with ignored invalid characters: "
<< j_invalid.dump(-1, ' ', false, json::error_handler_t::ignore)
<< '\n';
}

View File

@ -0,0 +1,3 @@
[json.exception.type_error.316] invalid UTF-8 byte at index 2: 0xA9
string with replaced invalid characters: "ä<>ü"
string with ignored invalid characters: "äü"

View File

@ -0,0 +1,20 @@
#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create byte vector
std::vector<std::uint8_t> v = {0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61,
0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68,
0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D
};
// deserialize it with BJData
json j = json::from_bjdata(v);
// print the deserialized JSON value
std::cout << std::setw(2) << j << std::endl;
}

View File

@ -0,0 +1,4 @@
{
"compact": true,
"schema": 0
}

View File

@ -0,0 +1,18 @@
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
auto alloc = json::get_allocator();
using traits_t = std::allocator_traits<decltype(alloc)>;
json* j = traits_t::allocate(alloc, 1);
traits_t::construct(alloc, j, "Hello, world!");
std::cout << *j << std::endl;
traits_t::destroy(alloc, j);
traits_t::deallocate(alloc, j, 1);
}

View File

@ -0,0 +1 @@
"Hello, world!"

View File

@ -1,29 +0,0 @@
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// create JSON values
json j_object = {{"one", 1}, {"two", 2}};
json j_array = {1, 2, 4, 8, 16};
//////////////////////////////////////////////////////////////////////////
// The static function iterator_wrapper was deprecated in version 3.1.0
// and will be removed in version 4.0.0. Please replace all occurrences
// of iterator_wrapper(j) with j.items().
//////////////////////////////////////////////////////////////////////////
// example for an object
for (auto& x : json::iterator_wrapper(j_object))
{
std::cout << "key: " << x.key() << ", value: " << x.value() << '\n';
}
// example for an array
for (auto& x : json::iterator_wrapper(j_array))
{
std::cout << "key: " << x.key() << ", value: " << x.value() << '\n';
}
}

View File

@ -1,7 +0,0 @@
key: one, value: 1
key: two, value: 2
key: 0, value: 1
key: 1, value: 2
key: 2, value: 4
key: 3, value: 8
key: 4, value: 16

View File

@ -0,0 +1,19 @@
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
// different JSON Pointers
json::json_pointer ptr1("/foo/0");
json::json_pointer ptr2("/a~1b");
// implicit conversion to string
std::string s;
s += ptr1;
s += "\n";
s += ptr2;
std::cout << s << std::endl;
}

View File

@ -0,0 +1,2 @@
/foo/0
/a~1b

View File

@ -0,0 +1,13 @@
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
json::json_pointer::string_t s = "This is a string.";
std::cout << s << std::endl;
std::cout << std::boolalpha << std::is_same<json::json_pointer::string_t, json::string_t>::value << std::endl;
}

View File

@ -0,0 +1,2 @@
This is a string.
true

View File

@ -19,7 +19,6 @@ int main()
json::json_pointer ptr11("/ "); json::json_pointer ptr11("/ ");
json::json_pointer ptr12("/m~0n"); json::json_pointer ptr12("/m~0n");
std::cout << ptr1.to_string() << '\n' std::cout << ptr1.to_string() << '\n'
<< ptr2.to_string() << '\n' << ptr2.to_string() << '\n'
<< ptr3.to_string() << '\n' << ptr3.to_string() << '\n'

View File

@ -0,0 +1,12 @@
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
std::cout << "JSON for Modern C++ version "
<< NLOHMANN_JSON_VERSION_MAJOR << "."
<< NLOHMANN_JSON_VERSION_MINOR << "."
<< NLOHMANN_JSON_VERSION_PATCH << std::endl;
}

View File

@ -0,0 +1 @@
JSON for Modern C++ version 3.10.5

View File

@ -0,0 +1,11 @@
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
std::cout << std::boolalpha
<< "json::object_comparator_t(\"one\", \"two\") = " << json::object_comparator_t{}("one", "two") << "\n"
<< "json::object_comparator_t(\"three\", \"four\") = " << json::object_comparator_t{}("three", "four") << std::endl;
}

View File

@ -0,0 +1,2 @@
json::object_comparator_t("one", "two") = true
json::object_comparator_t("three", "four") = false

View File

@ -0,0 +1,14 @@
#include <iostream>
#include <nlohmann/json.hpp>
using ordered_json = nlohmann::ordered_json;
int main()
{
ordered_json j;
j["one"] = 1;
j["two"] = 2;
j["three"] = 3;
std::cout << j.dump(2) << '\n';
}

View File

@ -0,0 +1,5 @@
{
"one": 1,
"two": 2,
"three": 3
}

View File

@ -6,7 +6,7 @@
using json = nlohmann::json; using json = nlohmann::json;
// a simple event consumer that collects string representations of the passed // a simple event consumer that collects string representations of the passed
// values; not inheriting from json::json_sax_t is not required, but can // values; note inheriting from json::json_sax_t is not required, but can
// help not to forget a required function // help not to forget a required function
class sax_event_consumer : public json::json_sax_t class sax_event_consumer : public json::json_sax_t
{ {
@ -15,79 +15,79 @@ class sax_event_consumer : public json::json_sax_t
bool null() override bool null() override
{ {
events.push_back("value: null"); events.push_back("null()");
return true; return true;
} }
bool boolean(bool val) override bool boolean(bool val) override
{ {
events.push_back("value: " + std::string(val ? "true" : "false")); events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
return true; return true;
} }
bool number_integer(number_integer_t val) override bool number_integer(number_integer_t val) override
{ {
events.push_back("value: " + std::to_string(val)); events.push_back("number_integer(val=" + std::to_string(val) + ")");
return true; return true;
} }
bool number_unsigned(number_unsigned_t val) override bool number_unsigned(number_unsigned_t val) override
{ {
events.push_back("value: " + std::to_string(val)); events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
return true; return true;
} }
bool number_float(number_float_t val, const string_t& s) override bool number_float(number_float_t val, const string_t& s) override
{ {
events.push_back("value: " + s); events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
return true; return true;
} }
bool string(string_t& val) override bool string(string_t& val) override
{ {
events.push_back("value: " + val); events.push_back("string(val=" + val + ")");
return true; return true;
} }
bool start_object(std::size_t elements) override bool start_object(std::size_t elements) override
{ {
events.push_back("start: object"); events.push_back("start_object(elements=" + std::to_string(elements) + ")");
return true; return true;
} }
bool end_object() override bool end_object() override
{ {
events.push_back("end: object"); events.push_back("end_object()");
return true; return true;
} }
bool start_array(std::size_t elements) override bool start_array(std::size_t elements) override
{ {
events.push_back("start: array"); events.push_back("start_array(elements=" + std::to_string(elements) + ")");
return true; return true;
} }
bool end_array() override bool end_array() override
{ {
events.push_back("end: array"); events.push_back("end_array()");
return true; return true;
} }
bool key(string_t& val) override bool key(string_t& val) override
{ {
events.push_back("key: " + val); events.push_back("key(val=" + val + ")");
return true; return true;
} }
bool binary(json::binary_t& val) override bool binary(json::binary_t& val) override
{ {
events.push_back("binary"); events.push_back("binary(val=[...])");
return true; return true;
} }
bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
{ {
events.push_back("error: " + std::string(ex.what())); events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
return false; return false;
} }
}; };
@ -107,22 +107,23 @@ int main()
"Width": 100 "Width": 100
}, },
"Animated" : false, "Animated" : false,
"IDs": [116, 943, 234, 38793], "IDs": [116, 943, 234, -38793],
"DeletionDate": null,
"Distance": 12.723374634 "Distance": 12.723374634
} }
} }]
)"; )";
// create a SAX event consumer object // create a SAX event consumer object
sax_event_consumer sec; sax_event_consumer sec;
// parse and serialize JSON // parse JSON
bool result = json::sax_parse(text, &sec); bool result = json::sax_parse(text, &sec);
// output the recorded events // output the recorded events
for (auto& event : sec.events) for (auto& event : sec.events)
{ {
std::cout << "(" << event << ") "; std::cout << event << "\n";
} }
// output the result of sax_parse // output the result of sax_parse

View File

@ -1,2 +1,37 @@
(start: object) (key: Image) (start: object) (key: Width) (value: 800) (key: Height) (value: 600) (key: Title) (value: View from 15th Floor) (key: Thumbnail) (start: object) (key: Url) (value: http://www.example.com/image/481989943) (key: Height) (value: 125) (key: Width) (value: 100) (end: object) (key: Animated) (value: false) (key: IDs) (start: array) (value: 116) (value: 943) (value: 234) (value: 38793) (end: array) (key: Distance) (value: 12.723374634) (end: object) (end: object) start_object(elements=18446744073709551615)
result: true key(val=Image)
start_object(elements=18446744073709551615)
key(val=Width)
number_unsigned(val=800)
key(val=Height)
number_unsigned(val=600)
key(val=Title)
string(val=View from 15th Floor)
key(val=Thumbnail)
start_object(elements=18446744073709551615)
key(val=Url)
string(val=http://www.example.com/image/481989943)
key(val=Height)
number_unsigned(val=125)
key(val=Width)
number_unsigned(val=100)
end_object()
key(val=Animated)
boolean(val=false)
key(val=IDs)
start_array(elements=18446744073709551615)
number_unsigned(val=116)
number_unsigned(val=943)
number_unsigned(val=234)
number_integer(val=-38793)
end_array()
key(val=DeletionDate)
null()
key(val=Distance)
number_float(val=12.723375, s=12.723374634)
end_object()
end_object()
parse_error(position=460, last_token=12.723374634<U+000A> }<U+000A> }],
ex=[json.exception.parse_error.101] parse error at line 17, column 6: syntax error while parsing value - unexpected ']'; expected end of input)
result: false

View File

@ -0,0 +1,114 @@
#include <iostream>
#include <iomanip>
#include <sstream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
// a simple event consumer that collects string representations of the passed
// values; note inheriting from json::json_sax_t is not required, but can
// help not to forget a required function
class sax_event_consumer : public json::json_sax_t
{
public:
std::vector<std::string> events;
bool null() override
{
events.push_back("null()");
return true;
}
bool boolean(bool val) override
{
events.push_back("boolean(val=" + std::string(val ? "true" : "false") + ")");
return true;
}
bool number_integer(number_integer_t val) override
{
events.push_back("number_integer(val=" + std::to_string(val) + ")");
return true;
}
bool number_unsigned(number_unsigned_t val) override
{
events.push_back("number_unsigned(val=" + std::to_string(val) + ")");
return true;
}
bool number_float(number_float_t val, const string_t& s) override
{
events.push_back("number_float(val=" + std::to_string(val) + ", s=" + s + ")");
return true;
}
bool string(string_t& val) override
{
events.push_back("string(val=" + val + ")");
return true;
}
bool start_object(std::size_t elements) override
{
events.push_back("start_object(elements=" + std::to_string(elements) + ")");
return true;
}
bool end_object() override
{
events.push_back("end_object()");
return true;
}
bool start_array(std::size_t elements) override
{
events.push_back("start_array(elements=" + std::to_string(elements) + ")");
return true;
}
bool end_array() override
{
events.push_back("end_array()");
return true;
}
bool key(string_t& val) override
{
events.push_back("key(val=" + val + ")");
return true;
}
bool binary(json::binary_t& val) override
{
events.push_back("binary(val=[...])");
return true;
}
bool parse_error(std::size_t position, const std::string& last_token, const json::exception& ex) override
{
events.push_back("parse_error(position=" + std::to_string(position) + ", last_token=" + last_token + ",\n ex=" + std::string(ex.what()) + ")");
return false;
}
};
int main()
{
// CBOR byte string
std::vector<std::uint8_t> vec = {{0x44, 0xcA, 0xfe, 0xba, 0xbe}};
// create a SAX event consumer object
sax_event_consumer sec;
// parse CBOR
bool result = json::sax_parse(vec, &sec, json::input_format_t::cbor);
// output the recorded events
for (auto& event : sec.events)
{
std::cout << event << "\n";
}
// output the result of sax_parse
std::cout << "\nresult: " << std::boolalpha << result << std::endl;
}

View File

@ -0,0 +1,3 @@
binary(val=[...])
result: true

View File

@ -0,0 +1,63 @@
#include <iostream>
#include <iomanip>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
// function to print BJData's diagnostic format
void print_byte(uint8_t byte)
{
if (32 < byte and byte < 128)
{
std::cout << (char)byte;
}
else
{
std::cout << (int)byte;
}
}
int main()
{
// create a JSON value
json j = R"({"compact": true, "schema": false})"_json;
// serialize it to BJData
std::vector<std::uint8_t> v = json::to_bjdata(j);
// print the vector content
for (auto& byte : v)
{
print_byte(byte);
}
std::cout << std::endl;
// create an array of numbers
json array = {1, 2, 3, 4, 5, 6, 7, 8};
// serialize it to BJData using default representation
std::vector<std::uint8_t> v_array = json::to_bjdata(array);
// serialize it to BJData using size optimization
std::vector<std::uint8_t> v_array_size = json::to_bjdata(array, true);
// serialize it to BJData using type optimization
std::vector<std::uint8_t> v_array_size_and_type = json::to_bjdata(array, true, true);
// print the vector contents
for (auto& byte : v_array)
{
print_byte(byte);
}
std::cout << std::endl;
for (auto& byte : v_array_size)
{
print_byte(byte);
}
std::cout << std::endl;
for (auto& byte : v_array_size_and_type)
{
print_byte(byte);
}
std::cout << std::endl;
}

View File

@ -0,0 +1,4 @@
{i7compactTi6schemaF}
[i1i2i3i4i5i6i7i8]
[#i8i1i2i3i4i5i6i7i8
[$i#i812345678

View File

@ -184,6 +184,7 @@ Strong exception safety: if an exception occurs, the original value stays intact
## See also ## See also
- documentation on [checked access](../../features/element_access/checked_access.md)
- see [`operator[]`](operator%5B%5D.md) for unchecked access by reference - see [`operator[]`](operator%5B%5D.md) for unchecked access by reference
- see [`value`](value.md) for access with default value - see [`value`](value.md) for access with default value

View File

@ -241,7 +241,7 @@ basic_json(basic_json&& other) noexcept;
- Overload 5: - Overload 5:
!!! note !!! note "Empty initializer list"
When used without parentheses around an empty initializer list, `basic_json()` is called instead of this When used without parentheses around an empty initializer list, `basic_json()` is called instead of this
function, yielding the JSON `#!json null` value. function, yielding the JSON `#!json null` value.

View File

@ -20,6 +20,23 @@ ignore
store store
: store tagged values as binary container with subtype (for bytes 0xd8..0xdb) : store tagged values as binary container with subtype (for bytes 0xd8..0xdb)
## Examples
??? example
The example below shows how the different values of the `cbor_tag_handler_t` influence the behavior of
[`from_cbor`](from_cbor.md) when reading a tagged byte string.
```cpp
--8<-- "examples/cbor_tag_handler_t.cpp"
```
Output:
```json
--8<-- "examples/cbor_tag_handler_t.output"
```
## Version history ## Version history
- Added in version 3.9.0. Added value `store` in 3.10.0. - Added in version 3.9.0. Added value `store` in 3.10.0.

View File

@ -60,8 +60,8 @@ Logarithmic in the size of the JSON object.
## Notes ## Notes
1. This method always returns `#!cpp false` when executed on a JSON type that is not an object. - This method always returns `#!cpp false` when executed on a JSON type that is not an object.
2. This method can be executed on any JSON value type. - This method can be executed on any JSON value type.
!!! info "Postconditions" !!! info "Postconditions"

View File

@ -14,6 +14,22 @@ when looking up a key in an object.
The actual comparator used depends on [`object_t`](object_t.md) and can be obtained via The actual comparator used depends on [`object_t`](object_t.md) and can be obtained via
[`object_comparator_t`](object_comparator_t.md). [`object_comparator_t`](object_comparator_t.md).
## Examples
??? example
The example below demonstrates the default comparator.
```cpp
--8<-- "examples/default_object_comparator_t.cpp"
```
Output:
```json
--8<-- "examples/default_object_comparator_t.output"
```
## Version history ## Version history
- Added in version 3.11.0. - Added in version 3.11.0.

View File

@ -20,6 +20,23 @@ replace
ignore ignore
: ignore invalid UTF-8 sequences; all bytes are copied to the output unchanged : ignore invalid UTF-8 sequences; all bytes are copied to the output unchanged
## Examples
??? example
The example below shows how the different values of the `error_handler_t` influence the behavior of
[`dump`](dump.md) when reading serializing an invalid UTF-8 sequence.
```cpp
--8<-- "examples/error_handler_t.cpp"
```
Output:
```json
--8<-- "examples/error_handler_t.output"
```
## Version history ## Version history
- Added in version 3.4.0. - Added in version 3.4.0.

View File

@ -0,0 +1,93 @@
# <small>nlohmann::basic_json::</small>from_bjdata
```cpp
// (1)
template<typename InputType>
static basic_json from_bjdata(InputType&& i,
const bool strict = true,
const bool allow_exceptions = true);
// (2)
template<typename IteratorType>
static basic_json from_bjdata(IteratorType first, IteratorType last,
const bool strict = true,
const bool allow_exceptions = true);
```
Deserializes a given input to a JSON value using the BJData (Binary JData) serialization format.
1. Reads from a compatible input.
2. Reads from an iterator range.
The exact mapping and its limitations is described on a [dedicated page](../../features/binary_formats/bjdata.md).
## Template parameters
`InputType`
: A compatible input, for instance:
- an `std::istream` object
- a `FILE` pointer
- a C-style array of characters
- a pointer to a null-terminated string of single byte characters
- an object `obj` for which `begin(obj)` and `end(obj)` produces a valid pair of iterators.
`IteratorType`
: a compatible iterator type
## Parameters
`i` (in)
: an input in BJData format convertible to an input adapter
`first` (in)
: iterator to start of the input
`last` (in)
: iterator to end of the input
`strict` (in)
: whether to expect the input to be consumed until EOF (`#!cpp true` by default)
`allow_exceptions` (in)
: whether to throw exceptions in case of a parse error (optional, `#!cpp true` by default)
## Return value
deserialized JSON value; in case of a parse error and `allow_exceptions` set to `#!cpp false`, the return value will be
`value_t::discarded`. The latter can be checked with [`is_discarded`](is_discarded.md).
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Exceptions
- Throws [parse_error.110](../../home/exceptions.md#jsonexceptionparse_error110) if the given input ends prematurely or
the end of file was not reached when `strict` was set to true
- Throws [parse_error.112](../../home/exceptions.md#jsonexceptionparse_error112) if a parse error occurs
- Throws [parse_error.113](../../home/exceptions.md#jsonexceptionparse_error113) if a string could not be parsed
successfully
## Complexity
Linear in the size of the input.
## Examples
??? example
The example shows the deserialization of a byte vector in BJData format to a JSON value.
```cpp
--8<-- "examples/from_bjdata.cpp"
```
Output:
```json
--8<-- "examples/from_bjdata.output"
```
## Version history
- Added in version 3.11.0.

View File

@ -10,10 +10,22 @@ Returns the allocator associated with the container.
associated allocator associated allocator
## Examples
??? example
The example shows how `get_allocator()` is used to created `json` values.
```cpp
--8<-- "examples/get_allocator.cpp"
```
Output:
```json
--8<-- "examples/get_allocator.output"
```
## Version history ## Version history
- Unknown. - Added in version 1.0.0.
!!! note
This documentation page is a stub.

View File

@ -233,9 +233,10 @@ Access to the JSON value
- [**operator==**](operator_eq.md) - comparison: equal - [**operator==**](operator_eq.md) - comparison: equal
- [**operator!=**](operator_ne.md) - comparison: not equal - [**operator!=**](operator_ne.md) - comparison: not equal
- [**operator<**](operator_lt.md) - comparison: less than - [**operator<**](operator_lt.md) - comparison: less than
- [**operator<=**](operator_le.md) - comparison: less than or equal
- [**operator>**](operator_gt.md) - comparison: greater than - [**operator>**](operator_gt.md) - comparison: greater than
- [**operator<=**](operator_le.md) - comparison: less than or equal
- [**operator>=**](operator_ge.md) - comparison: greater than or equal - [**operator>=**](operator_ge.md) - comparison: greater than or equal
- [**operator<=>**](operator_spaceship.md) - comparison: 3-way
### Serialization / Dumping ### Serialization / Dumping
@ -268,10 +269,12 @@ Access to the JSON value
### Binary formats ### Binary formats
- [**from_bjdata**](from_bjdata.md) (_static_) - create a JSON value from an input in BJData format
- [**from_bson**](from_bson.md) (_static_) - create a JSON value from an input in BSON format - [**from_bson**](from_bson.md) (_static_) - create a JSON value from an input in BSON format
- [**from_cbor**](from_cbor.md) (_static_) - create a JSON value from an input in CBOR format - [**from_cbor**](from_cbor.md) (_static_) - create a JSON value from an input in CBOR format
- [**from_msgpack**](from_msgpack.md) (_static_) - create a JSON value from an input in MessagePack format - [**from_msgpack**](from_msgpack.md) (_static_) - create a JSON value from an input in MessagePack format
- [**from_ubjson**](from_ubjson.md) (_static_) - create a JSON value from an input in UBJSON format - [**from_ubjson**](from_ubjson.md) (_static_) - create a JSON value from an input in UBJSON format
- [**to_bjdata**](to_bjdata.md) (_static_) - create a BJData serialization of a given JSON value
- [**to_bson**](to_bson.md) (_static_) - create a BSON serialization of a given JSON value - [**to_bson**](to_bson.md) (_static_) - create a BSON serialization of a given JSON value
- [**to_cbor**](to_cbor.md) (_static_) - create a CBOR serialization of a given JSON value - [**to_cbor**](to_cbor.md) (_static_) - create a CBOR serialization of a given JSON value
- [**to_msgpack**](to_msgpack.md) (_static_) - create a MessagePack serialization of a given JSON value - [**to_msgpack**](to_msgpack.md) (_static_) - create a MessagePack serialization of a given JSON value

View File

@ -6,7 +6,8 @@ enum class input_format_t {
cbor, cbor,
msgpack, msgpack,
ubjson, ubjson,
bson bson,
bjdata
}; };
``` ```
@ -27,6 +28,25 @@ ubjson
bson bson
: BSON (Binary JSON) : BSON (Binary JSON)
bjdata
: BJData (Binary JData)
## Examples
??? example
The example below shows how an `input_format_t` enum value is passed to `sax_parse` to set the input format to CBOR.
```cpp
--8<-- "examples/sax_parse__binary.cpp"
```
Output:
```json
--8<-- "examples/sax_parse__binary.output"
```
## Version history ## Version history
- Added in version 3.2.0. - Added in version 3.2.0.

View File

@ -1,6 +1,5 @@
# <small>nlohmann::basic_json::</small>object_comparator_t # <small>nlohmann::basic_json::</small>object_comparator_t
```cpp ```cpp
using object_comparator_t = typename object_t::key_compare; using object_comparator_t = typename object_t::key_compare;
// or // or
@ -10,6 +9,22 @@ using object_comparator_t = default_object_comparator_t;
The comparator used by [`object_t`](object_t.md). Defined as `#!cpp typename object_t::key_compare` if available, The comparator used by [`object_t`](object_t.md). Defined as `#!cpp typename object_t::key_compare` if available,
and [`default_object_comparator_t`](default_object_comparator_t.md) otherwise. and [`default_object_comparator_t`](default_object_comparator_t.md) otherwise.
## Examples
??? example
The example below demonstrates the used object comparator.
```cpp
--8<-- "examples/object_comparator_t.cpp"
```
Output:
```json
--8<-- "examples/object_comparator_t.output"
```
## Version history ## Version history
- Added in version 3.0.0. - Added in version 3.0.0.

View File

@ -41,12 +41,9 @@ reference operator+=(initializer_list_t init);
## Exceptions ## Exceptions
1. The function can throw the following exceptions: All functions can throw the following exception:
- Throws [`type_error.308`](../../home/exceptions.md#jsonexceptiontype_error308) when called on a type other than - Throws [`type_error.308`](../../home/exceptions.md#jsonexceptiontype_error308) when called on a type other than
JSON array or null; example: `"cannot use operator+=() with number"` JSON array or null; example: `"cannot use operator+=() with number"`
2. The function can throw the following exceptions:
- Throws [`type_error.308`](../../home/exceptions.md#jsonexceptiontype_error308) when called on a type other than
JSON object or null; example: `"cannot use operator+=() with number"`
## Complexity ## Complexity

View File

@ -198,6 +198,8 @@ Strong exception safety: if an exception occurs, the original value stays intact
## See also ## See also
- documentation on [unchecked access](../../features/element_access/unchecked_access.md)
- documentation on [runtime assertions](../../features/assertions.md)
- see [`at`](at.md) for access by reference with range checking - see [`at`](at.md) for access by reference with range checking
- see [`value`](value.md) for access with default value - see [`value`](value.md) for access with default value

View File

@ -56,7 +56,6 @@ Linear in the size of the JSON value.
[`JSON_USE_IMPLICIT_CONVERSIONS`](../macros/json_use_implicit_conversions.md) to `0` and replace any implicit [`JSON_USE_IMPLICIT_CONVERSIONS`](../macros/json_use_implicit_conversions.md) to `0` and replace any implicit
conversions with calls to [`get`](../basic_json/get.md). conversions with calls to [`get`](../basic_json/get.md).
## Examples ## Examples
??? example ??? example

View File

@ -1,21 +1,31 @@
# <small>nlohmann::basic_json::</small>operator== # <small>nlohmann::basic_json::</small>operator==
```cpp ```cpp
bool operator==(const_reference lhs, const_reference rhs) noexcept; // until C++20
bool operator==(const_reference lhs, const_reference rhs) noexcept; // (1)
template<typename ScalarType> template<typename ScalarType>
bool operator==(const_reference lhs, const ScalarType rhs) noexcept; bool operator==(const_reference lhs, const ScalarType rhs) noexcept; // (2)
template<typename ScalarType> template<typename ScalarType>
bool operator==(ScalarType lhs, const const_reference rhs) noexcept; bool operator==(ScalarType lhs, const const_reference rhs) noexcept; // (2)
// since C++20
class basic_json {
bool operator==(const_reference rhs) const noexcept; // (1)
template<typename ScalarType>
bool operator==(ScalarType rhs) const noexcept; // (2)
};
``` ```
Compares two JSON values for equality according to the following rules: 1. Compares two JSON values for equality according to the following rules:
- Two JSON values are equal if (1) neither value is discarded, or (2) they are of the same
type and their stored values are the same according to their respective `operator==`.
- Integer and floating-point numbers are automatically converted before comparison.
- Two JSON values are equal if (1) they are not discarded, (2) they are from the same type, and (3) their stored values 2. Compares a JSON value and a scalar or a scalar and a JSON value for equality by converting the
are the same according to their respective `operator==`. scalar to a JSON value and comparing both JSON values according to 1.
- Integer and floating-point numbers are automatically converted before comparison. Note that two NaN values are always
treated as unequal.
## Template parameters ## Template parameters
@ -32,7 +42,7 @@ Compares two JSON values for equality according to the following rules:
## Return value ## Return value
whether the values `lhs` and `rhs` are equal whether the values `lhs`/`*this` and `rhs` are equal
## Exception safety ## Exception safety
@ -44,13 +54,17 @@ Linear.
## Notes ## Notes
!!! note !!! note "Comparing special values"
- NaN values never compare equal to themselves or to other NaN values. - `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.
- JSON `#!cpp null` values are all equal. - JSON `#!cpp null` values are all equal.
- Discarded values never compare equal to themselves. - Discarded values never compare equal to themselves.
!!! note !!! note "Comparing floating-point numbers"
Floating-point numbers inside JSON values numbers are compared with `json::number_float_t::operator==` which is Floating-point numbers inside JSON values numbers are compared with `json::number_float_t::operator==` which is
`double::operator==` by default. To compare floating-point while respecting an epsilon, an alternative `double::operator==` by default. To compare floating-point while respecting an epsilon, an alternative
@ -117,4 +131,5 @@ Linear.
## Version history ## Version history
- Added in version 1.0.0. 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.

View File

@ -1,17 +1,25 @@
# <small>nlohmann::basic_json::</small>operator>= # <small>nlohmann::basic_json::</small>operator>=
```cpp ```cpp
bool operator>=(const_reference lhs, const_reference rhs) noexcept, // until C++20
bool operator>=(const_reference lhs, const_reference rhs) noexcept; // (1)
template<typename ScalarType> template<typename ScalarType>
bool operator>=(const_reference lhs, const ScalarType rhs) noexcept; bool operator>=(const_reference lhs, const ScalarType rhs) noexcept; // (2)
template<typename ScalarType> template<typename ScalarType>
bool operator>=(ScalarType lhs, const const_reference rhs) noexcept; bool operator>=(ScalarType lhs, const const_reference rhs) noexcept; // (2)
``` ```
Compares whether one JSON value `lhs` is greater than or equal to another JSON value `rhs` by calculating 1. Compares whether one JSON value `lhs` is greater than or equal to another JSON value `rhs`
`#!cpp !(lhs < rhs)`. 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)`.
2. Compares wether a JSON value is greater than or equal to a scalar or a scalar is greater than or
equal to a JSON value by converting the scalar to a JSON value and comparing both JSON values
according to 1.
## Template parameters ## Template parameters
@ -38,6 +46,21 @@ No-throw guarantee: this function never throws exceptions.
Linear. Linear.
## Notes
!!! note "Comparing `NaN`"
`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.
!!! note "Operator overload resolution"
Since C++20 overload resolution will consider the _rewritten candidate_ generated from
[`operator<=>`](operator_spaceship.md).
## Examples ## Examples
??? example ??? example
@ -54,6 +77,11 @@ Linear.
--8<-- "examples/operator__greaterequal.output" --8<-- "examples/operator__greaterequal.output"
``` ```
## See also
- [**operator<=>**](operator_spaceship.md) comparison: 3-way
## Version history ## Version history
- Added in version 1.0.0. 1. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
2. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.

View File

@ -1,16 +1,24 @@
# <small>nlohmann::basic_json::</small>operator> # <small>nlohmann::basic_json::</small>operator>
```cpp ```cpp
bool operator>(const_reference lhs, const_reference rhs) noexcept, // until C++20
bool operator>(const_reference lhs, const_reference rhs) noexcept; // (1)
template<typename ScalarType> template<typename ScalarType>
bool operator>(const_reference lhs, const ScalarType rhs) noexcept; bool operator>(const_reference lhs, const ScalarType rhs) noexcept; // (2)
template<typename ScalarType> template<typename ScalarType>
bool operator>(ScalarType lhs, const const_reference rhs) noexcept; bool operator>(ScalarType lhs, const const_reference rhs) noexcept; // (2)
``` ```
Compares whether one JSON value `lhs` is greater than another JSON value `rhs` by calculating `#!cpp !(lhs <= rhs)`. 1. Compares whether one JSON value `lhs` is greater than another JSON value `rhs` 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)`.
2. Compares wether a JSON value is greater than a scalar or a scalar is greater than a JSON value by
converting the scalar to a JSON value and comparing both JSON values according to 1.
## Template parameters ## Template parameters
@ -37,6 +45,21 @@ No-throw guarantee: this function never throws exceptions.
Linear. Linear.
## Notes
!!! note "Comparing `NaN`"
`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.
!!! note "Operator overload resolution"
Since C++20 overload resolution will consider the _rewritten candidate_ generated from
[`operator<=>`](operator_spaceship.md).
## Examples ## Examples
??? example ??? example
@ -53,6 +76,11 @@ Linear.
--8<-- "examples/operator__greater.output" --8<-- "examples/operator__greater.output"
``` ```
## See also
- [**operator<=>**](operator_spaceship.md) comparison: 3-way
## Version history ## Version history
- Added in version 1.0.0. 1. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
2. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.

View File

@ -1,17 +1,25 @@
# <small>nlohmann::basic_json::</small>operator<= # <small>nlohmann::basic_json::</small>operator<=
```cpp ```cpp
bool operator<=(const_reference lhs, const_reference rhs) noexcept, // until C++20
bool operator<=(const_reference lhs, const_reference rhs) noexcept; // (1)
template<typename ScalarType> template<typename ScalarType>
bool operator<=(const_reference lhs, const ScalarType rhs) noexcept; bool operator<=(const_reference lhs, const ScalarType rhs) noexcept; // (2)
template<typename ScalarType> template<typename ScalarType>
bool operator<=(ScalarType lhs, const const_reference rhs) noexcept; bool operator<=(ScalarType lhs, const const_reference rhs) noexcept; // (2)
``` ```
Compares whether one JSON value `lhs` is less than or equal to another JSON value `rhs` by calculating 1. Compares whether one JSON value `lhs` is less than or equal to another JSON value `rhs`
`#cpp !(rhs < lhs)`. 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 !(rhs < lhs)`.
1. Compares wether a JSON value is less than or equal to a scalar or a scalar is less than or equal
to a JSON value by converting the scalar to a JSON value and comparing both JSON values according
to 1.
## Template parameters ## Template parameters
@ -38,6 +46,21 @@ No-throw guarantee: this function never throws exceptions.
Linear. Linear.
## Notes
!!! note "Comparing `NaN`"
`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.
!!! note "Operator overload resolution"
Since C++20 overload resolution will consider the _rewritten candidate_ generated from
[`operator<=>`](operator_spaceship.md).
## Examples ## Examples
??? example ??? example
@ -54,6 +77,11 @@ Linear.
--8<-- "examples/operator__lessequal.output" --8<-- "examples/operator__lessequal.output"
``` ```
## See also
- [**operator<=>**](operator_spaceship.md) comparison: 3-way
## Version history ## Version history
- Added in version 1.0.0. 1. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
2. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.

View File

@ -1,31 +1,34 @@
# <small>nlohmann::basic_json::</small>operator< # <small>nlohmann::basic_json::</small>operator<
```cpp ```cpp
bool operator<(const_reference lhs, const_reference rhs) noexcept; // until C++20
bool operator<(const_reference lhs, const_reference rhs) noexcept; // (1)
template<typename ScalarType> template<typename ScalarType>
bool operator<(const_reference lhs, const ScalarType rhs) noexcept; bool operator<(const_reference lhs, const ScalarType rhs) noexcept; // (2)
template<typename ScalarType> template<typename ScalarType>
bool operator<(ScalarType lhs, const const_reference rhs) noexcept; bool operator<(ScalarType lhs, const const_reference rhs) noexcept; // (2)
``` ```
Compares whether one JSON value `lhs` is less than another JSON value `rhs` according to the following rules: 1. Compares whether one JSON value `lhs` is less than another JSON value `rhs` according to the
following rules:
- If either operand is discarded, the comparison yields `#!cpp false`.
- If both operands have the same type, the values are compared using their respective `operator<`.
- Integer and floating-point numbers are automatically converted before comparison.
- In case `lhs` and `rhs` have different types, the values are ignored and the order of the types
is considered, which is:
1. null
2. boolean
3. number (all types)
4. object
5. array
6. string
7. binary
For instance, any boolean value is considered less than any string.
- If `lhs` and `rhs` have the same type, the values are compared using the default `<` operator. 2. Compares wether a JSON value is less than a scalar or a scalar is less than a JSON value by converting
- Integer and floating-point numbers are automatically converted before comparison the scalar to a JSON value and comparing both JSON values according to 1.
- Discarded values a
- In case `lhs` and `rhs` have different types, the values are ignored and the order of the types is considered, which
is:
1. null
2. boolean
3. number (all types)
4. object
5. array
6. string
7. binary
For instance, any boolean value is considered less than any string.
## Template parameters ## Template parameters
@ -52,6 +55,21 @@ No-throw guarantee: this function never throws exceptions.
Linear. Linear.
## Notes
!!! note "Comparing `NaN`"
`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.
!!! note "Operator overload resolution"
Since C++20 overload resolution will consider the _rewritten candidate_ generated from
[`operator<=>`](operator_spaceship.md).
## Examples ## Examples
??? example ??? example
@ -68,6 +86,11 @@ Linear.
--8<-- "examples/operator__less.output" --8<-- "examples/operator__less.output"
``` ```
## See also
- [**operator<=>**](operator_spaceship.md) comparison: 3-way
## Version history ## Version history
- Added in version 1.0.0. 1. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.
2. Added in version 1.0.0. Conditionally removed since C++20 in version 3.11.0.

View File

@ -1,16 +1,32 @@
# <small>nlohmann::basic_json::</small>operator!= # <small>nlohmann::basic_json::</small>operator!=
```cpp ```cpp
bool operator!=(const_reference lhs, const_reference rhs) noexcept; // until C++20
bool operator!=(const_reference lhs, const_reference rhs) noexcept; // (1)
template<typename ScalarType> template<typename ScalarType>
bool operator!=(const_reference lhs, const ScalarType rhs) noexcept; bool operator!=(const_reference lhs, const ScalarType rhs) noexcept; // (2)
template<typename ScalarType> template<typename ScalarType>
bool operator!=(ScalarType lhs, const const_reference rhs) noexcept; bool operator!=(ScalarType lhs, const const_reference rhs) noexcept; // (2)
// since C++20
class basic_json {
bool operator!=(const_reference rhs) const noexcept; // (1)
template<typename ScalarType>
bool operator!=(ScalarType rhs) const noexcept; // (2)
};
``` ```
Compares two JSON values for inequality by calculating `#!cpp !(lhs == rhs)`. 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.
## Template parameters ## Template parameters
@ -27,7 +43,7 @@ Compares two JSON values for inequality by calculating `#!cpp !(lhs == rhs)`.
## Return value ## Return value
whether the values `lhs` and `rhs` are not equal whether the values `lhs`/`*this` and `rhs` are not equal
## Exception safety ## Exception safety
@ -37,6 +53,16 @@ No-throw guarantee: this function never throws exceptions.
Linear. Linear.
## Notes
!!! note "Comparing `NaN`"
`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 ## Examples
??? example ??? example
@ -69,4 +95,5 @@ Linear.
## Version history ## Version history
- Added in version 1.0.0. 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.

View File

@ -0,0 +1,70 @@
# <small>nlohmann::basic_json::</small>operator<=>
```cpp
// since C++20
class basic_json {
std::partial_ordering operator<=>(const_reference rhs) const noexcept; // (1)
template<typename ScalarType>
std::partial_ordering operator<=>(const ScalarType rhs) const noexcept; // (2)
};
```
1. 3-way compares two JSON values producing a result of type `std::partial_ordering` according to the following rules:
- Two JSON values compare with a result of `std::partial_ordering::unordered` if either value is discarded.
- If both JSON values are of the same type, the result is produced by 3-way comparing their stored values using their
respective `operator<=>`.
- Integer and floating-point numbers are converted to their common type and then 3-way compared using their respective
`operator<=>`.
For instance, comparing an integer and a floating-point value will 3-way compare the first value convertered to
floating-point with the second value.
- Otherwise, yields a result by comparing the type (see [`value_t`](value_t.md)).
2. 3-way compares a JSON value and a scalar or a scalar and a JSON value by converting the scalar to a JSON value and 3-way
comparing both JSON values (see 1).
## Template parameters
`ScalarType`
: a scalar type according to `std::is_scalar<ScalarType>::value`
## Parameters
`rhs` (in)
: second value to consider
## Return value
the `std::partial_ordering` of the 3-way comparison of `*this` and `rhs`
## Exception safety
No-throw guarantee: this function never throws exceptions.
## Complexity
Linear.
## Notes
!!! note "Comparing `NaN`"
- `NaN` values are unordered within the domain of numbers.
The following comparisons all yield `std::partial_ordering::unordered`:
1. Comparing a `NaN` with itself.
2. Comparing a `NaN` with another `NaN`.
3. Comparing a `NaN` and any other number.
## See also
- [**operator==**](operator_eq.md) - comparison: equal
- [**operator!=**](operator_ne.md) - comparison: not equal
- [**operator<**](operator_lt.md) - comparison: less than
- [**operator<=**](operator_le.md) - comparison: less than or equal
- [**operator>**](operator_gt.md) - comparison: greater than
- [**operator>=**](operator_ge.md) - comparison: greater than or equal
## Version history
1. Added in version 3.11.0.
2. Added in version 3.11.0.

View File

@ -37,12 +37,9 @@ void push_back(initializer_list_t init);
## Exceptions ## Exceptions
1. The function can throw the following exceptions: All functions can throw the following exception:
- Throws [`type_error.308`](../../home/exceptions.md#jsonexceptiontype_error308) when called on a type other than - Throws [`type_error.308`](../../home/exceptions.md#jsonexceptiontype_error308) when called on a type other than
JSON array or null; example: `"cannot use push_back() with number"` JSON array or null; example: `"cannot use push_back() with number"`
2. The function can throw the following exceptions:
- Throws [`type_error.308`](../../home/exceptions.md#jsonexceptiontype_error308) when called on a type other than
JSON object or null; example: `"cannot use push_back() with number"`
## Complexity ## Complexity

View File

@ -0,0 +1,70 @@
# <small>nlohmann::basic_json::</small>to_bjdata
```cpp
// (1)
static std::vector<std::uint8_t> to_bjdata(const basic_json& j,
const bool use_size = false,
const bool use_type = false);
// (2)
static void to_bjdata(const basic_json& j, detail::output_adapter<std::uint8_t> o,
const bool use_size = false, const bool use_type = false);
static void to_bjdata(const basic_json& j, detail::output_adapter<char> o,
const bool use_size = false, const bool use_type = false);
```
Serializes a given JSON value `j` to a byte vector using the BJData (Binary JData) serialization format. BJData
aims to be more compact than JSON itself, yet more efficient to parse.
1. Returns a byte vector containing the BJData serialization.
2. Writes the BJData serialization to an output adapter.
The exact mapping and its limitations is described on a [dedicated page](../../features/binary_formats/bjdata.md).
## Parameters
`j` (in)
: JSON value to serialize
`o` (in)
: output adapter to write serialization to
`use_size` (in)
: whether to add size annotations to container types; optional, `#!cpp false` by default.
`use_type` (in)
: whether to add type annotations to container types (must be combined with `#!cpp use_size = true`); optional,
`#!cpp false` by default.
## Return value
1. BJData serialization as byte vector
2. (none)
## Exception safety
Strong guarantee: if an exception is thrown, there are no changes in the JSON value.
## Complexity
Linear in the size of the JSON value `j`.
## Examples
??? example
The example shows the serialization of a JSON value to a byte vector in BJData format.
```cpp
--8<-- "examples/to_bjdata.cpp"
```
Output:
```json
--8<-- "examples/to_bjdata.output"
```
## Version history
- Added in version 3.11.0.

View File

@ -24,10 +24,57 @@ functions [`is_null`](is_null.md), [`is_object`](is_object.md), [`is_array`](is_
## Notes ## Notes
There are three enumeration entries (number_integer, number_unsigned, and number_float), because the library !!! note "Ordering"
distinguishes these three types for numbers: [`number_unsigned_t`](number_unsigned_t.md) is used for unsigned integers,
[`number_integer_t`](number_integer_t.md) is used for signed integers, and [`number_float_t`](number_float_t.md) is used The order of types is as follows:
for floating-point numbers or to approximate integers which do not fit in the limits of their respective type.
1. `null`
2. `boolean`
3. `number_integer`, `number_unsigned`, `number_float`
4. `object`
5. `array`
6. `string`
7. `binary`
`discarded` is unordered.
!!! note "Types of numbers"
There are three enumerators for numbers (`number_integer`, `number_unsigned`, and `number_float`) to distinguish
between different types of numbers:
- [`number_unsigned_t`](number_unsigned_t.md) for unsigned integers
- [`number_integer_t`](number_integer_t.md) for signed integers
- [`number_float_t`](number_float_t.md) for floating-point numbers or to approximate integers which do not fit
into the limits of their respective type
!!! warning "Comparison operators"
`operator<` and `operator<=>` (since C++20) are overloaded and compare according to the ordering described above.
Until C++20 all other relational and equality operators yield results according to the integer value of each
enumerator.
Since C++20 some compilers consider the _rewritten candidates_ generated from `operator<=>` during overload
resolution, while others do not.
For predictable and portable behavior use:
- `operator<` or `operator<=>` when wanting to compare according to the order described above
- `operator==` or `operator!=` when wanting to compare according to each enumerators integer value
## Examples
??? example
The following code how `type()` queries the `value_t` for all JSON types.
```cpp
--8<-- "examples/type.cpp"
```
Output:
```json
--8<-- "examples/type.output"
```
## Version history ## Version history

View File

@ -25,6 +25,22 @@ byte_container_with_subtype(container_type&& container, subtype_type subtype);
`subtype` (in) `subtype` (in)
: subtype : subtype
## Examples
??? example
The example below demonstrates how byte containers can be created.
```cpp
--8<-- "examples/byte_container_with_subtype__byte_container_with_subtype.cpp"
```
Output:
```json
--8<-- "examples/byte_container_with_subtype__byte_container_with_subtype.output"
```
## Version history ## Version history
Since version 3.8.0. Since version 3.8.0.

View File

@ -15,6 +15,22 @@ No-throw guarantee: this function never throws exceptions.
Constant. Constant.
## Examples
??? example
The example below demonstrates how `clear_subtype` can remove subtypes.
```cpp
--8<-- "examples/byte_container_with_subtype__clear_subtype.cpp"
```
Output:
```json
--8<-- "examples/byte_container_with_subtype__clear_subtype.output"
```
## Version history ## Version history
Since version 3.8.0. Since version 3.8.0.

View File

@ -18,6 +18,22 @@ No-throw guarantee: this function never throws exceptions.
Constant. Constant.
## Examples
??? example
The example below demonstrates how `has_subtype` can check whether a subtype was set.
```cpp
--8<-- "examples/byte_container_with_subtype__has_subtype.cpp"
```
Output:
```json
--8<-- "examples/byte_container_with_subtype__has_subtype.output"
```
## Version history ## Version history
Since version 3.8.0. Since version 3.8.0.

View File

@ -20,6 +20,22 @@ No-throw guarantee: this function never throws exceptions.
Constant. Constant.
## Examples
??? example
The example below demonstrates how a subtype can be set with `set_subtype`.
```cpp
--8<-- "examples/byte_container_with_subtype__set_subtype.cpp"
```
Output:
```json
--8<-- "examples/byte_container_with_subtype__set_subtype.output"
```
## Version history ## Version history
Since version 3.8.0. Since version 3.8.0.

View File

@ -19,6 +19,23 @@ No-throw guarantee: this function never throws exceptions.
Constant. Constant.
## Examples
??? example
The example below demonstrates how the subtype can be retrieved with `subtype`. Note how `subtype_type(-1)` is
returned for container `c1`.
```cpp
--8<-- "examples/byte_container_with_subtype__subtype.cpp"
```
Output:
```json
--8<-- "examples/byte_container_with_subtype__subtype.output"
```
## Version history ## Version history
- Added in version 3.8.0 - Added in version 3.8.0

View File

@ -7,6 +7,22 @@ using json = basic_json<>;
This type is the default specialization of the [basic_json](basic_json/index.md) class which uses the standard template This type is the default specialization of the [basic_json](basic_json/index.md) class which uses the standard template
types. types.
## Examples
??? example
The example below demonstrates how to use the type `nlohmann::json`.
```cpp
--8<-- "examples/README.cpp"
```
Output:
```json
--8<-- "examples/README.output"
```
## Version history ## Version history
Since version 1.0.0. Since version 1.0.0.

View File

@ -14,11 +14,11 @@ are the base for JSON patches.
`RefStringType` `RefStringType`
: the string type used for the reference tokens making up the JSON pointer : the string type used for the reference tokens making up the JSON pointer
## Notes !!! warning "Deprecation"
For backwards compatibility `RefStringType` may also be a specialization of [`basic_json`](../basic_json/index.md) in For backwards compatibility `RefStringType` may also be a specialization of [`basic_json`](../basic_json/index.md)
which case `string_t` will be deduced as [`basic_json::string_t`](../basic_json/string_t.md). This feature is deprecated in which case `string_t` will be deduced as [`basic_json::string_t`](../basic_json/string_t.md). This feature is
and may be removed in a future major version. deprecated and may be removed in a future major version.
## Member types ## Member types

View File

@ -19,6 +19,22 @@ operator string_t() const
} }
``` ```
## Examples
??? example
The example shows how JSON Pointers can be implicitly converted to strings.
```cpp
--8<-- "examples/json_pointer__operator_string.cpp"
```
Output:
```json
--8<-- "examples/json_pointer__operator_string.output"
```
## Version history ## Version history
- Since version 2.0.0. - Since version 2.0.0.

View File

@ -7,6 +7,22 @@ The string type used for the reference tokens making up the JSON pointer.
See [`basic_json::string_t`](../basic_json/string_t.md) for more information. See [`basic_json::string_t`](../basic_json/string_t.md) for more information.
## Examples
??? example
The example shows the type `string_t` and its relation to `basic_json::string_t`.
```cpp
--8<-- "examples/json_pointer__string_t.cpp"
```
Output:
```json
--8<-- "examples/json_pointer__string_t.output"
```
## Version history ## Version history
- Added in version 3.11.0. - Added in version 3.11.0.

View File

@ -19,6 +19,22 @@ Whether parsing should proceed.
It is safe to move the passed binary value. It is safe to move the passed binary value.
## Examples
??? example
.The example below shows how the SAX interface is used.
```cpp
--8<-- "examples/sax_parse__binary.cpp"
```
Output:
```json
--8<-- "examples/sax_parse__binary.output"
```
## Version history ## Version history
- Added in version 3.8.0. - Added in version 3.8.0.

View File

@ -15,6 +15,22 @@ A boolean value was read.
Whether parsing should proceed. Whether parsing should proceed.
## Examples
??? example
.The example below shows how the SAX interface is used.
```cpp
--8<-- "examples/sax_parse.cpp"
```
Output:
```json
--8<-- "examples/sax_parse.output"
```
## Version history ## Version history
- Added in version 3.2.0. - Added in version 3.2.0.

View File

@ -10,6 +10,22 @@ The end of an array was read.
Whether parsing should proceed. Whether parsing should proceed.
## Examples
??? example
.The example below shows how the SAX interface is used.
```cpp
--8<-- "examples/sax_parse.cpp"
```
Output:
```json
--8<-- "examples/sax_parse.output"
```
## Version history ## Version history
- Added in version 3.2.0. - Added in version 3.2.0.

View File

@ -10,6 +10,22 @@ The end of an object was read.
Whether parsing should proceed. Whether parsing should proceed.
## Examples
??? example
.The example below shows how the SAX interface is used.
```cpp
--8<-- "examples/sax_parse.cpp"
```
Output:
```json
--8<-- "examples/sax_parse.output"
```
## Version history ## Version history
- Added in version 3.2.0. - Added in version 3.2.0.

View File

@ -19,6 +19,22 @@ Whether parsing should proceed.
It is safe to move the passed object key value. It is safe to move the passed object key value.
## Examples
??? example
.The example below shows how the SAX interface is used.
```cpp
--8<-- "examples/sax_parse.cpp"
```
Output:
```json
--8<-- "examples/sax_parse.output"
```
## Version history ## Version history
- Added in version 3.2.0. - Added in version 3.2.0.

View File

@ -10,6 +10,22 @@ A null value was read.
Whether parsing should proceed. Whether parsing should proceed.
## Examples
??? example
.The example below shows how the SAX interface is used.
```cpp
--8<-- "examples/sax_parse.cpp"
```
Output:
```json
--8<-- "examples/sax_parse.output"
```
## Version history ## Version history
- Added in version 3.2.0. - Added in version 3.2.0.

View File

@ -18,6 +18,22 @@ A floating-point number was read.
Whether parsing should proceed. Whether parsing should proceed.
## Examples
??? example
.The example below shows how the SAX interface is used.
```cpp
--8<-- "examples/sax_parse.cpp"
```
Output:
```json
--8<-- "examples/sax_parse.output"
```
## Version history ## Version history
- Added in version 3.2.0. - Added in version 3.2.0.

View File

@ -15,6 +15,22 @@ An integer number was read.
Whether parsing should proceed. Whether parsing should proceed.
## Examples
??? example
.The example below shows how the SAX interface is used.
```cpp
--8<-- "examples/sax_parse.cpp"
```
Output:
```json
--8<-- "examples/sax_parse.output"
```
## Version history ## Version history
- Added in version 3.2.0. - Added in version 3.2.0.

View File

@ -15,6 +15,22 @@ An unsigned integer number was read.
Whether parsing should proceed. Whether parsing should proceed.
## Examples
??? example
.The example below shows how the SAX interface is used.
```cpp
--8<-- "examples/sax_parse.cpp"
```
Output:
```json
--8<-- "examples/sax_parse.output"
```
## Version history ## Version history
- Added in version 3.2.0. - Added in version 3.2.0.

View File

@ -23,6 +23,22 @@ A parse error occurred.
Whether parsing should proceed (**must return `#!cpp false`**). Whether parsing should proceed (**must return `#!cpp false`**).
## Examples
??? example
.The example below shows how the SAX interface is used.
```cpp
--8<-- "examples/sax_parse.cpp"
```
Output:
```json
--8<-- "examples/sax_parse.output"
```
## Version history ## Version history
- Added in version 3.2.0. - Added in version 3.2.0.

View File

@ -19,6 +19,22 @@ Whether parsing should proceed.
Binary formats may report the number of elements. Binary formats may report the number of elements.
## Examples
??? example
.The example below shows how the SAX interface is used.
```cpp
--8<-- "examples/sax_parse.cpp"
```
Output:
```json
--8<-- "examples/sax_parse.output"
```
## Version history ## Version history
- Added in version 3.2.0. - Added in version 3.2.0.

View File

@ -19,6 +19,22 @@ Whether parsing should proceed.
Binary formats may report the number of elements. Binary formats may report the number of elements.
## Examples
??? example
.The example below shows how the SAX interface is used.
```cpp
--8<-- "examples/sax_parse.cpp"
```
Output:
```json
--8<-- "examples/sax_parse.output"
```
## Version history ## Version history
- Added in version 3.2.0. - Added in version 3.2.0.

View File

@ -19,6 +19,22 @@ Whether parsing should proceed.
It is safe to move the passed string value. It is safe to move the passed string value.
## Examples
??? example
.The example below shows how the SAX interface is used.
```cpp
--8<-- "examples/sax_parse.cpp"
```
Output:
```json
--8<-- "examples/sax_parse.output"
```
## Version history ## Version history
- Added in version 3.2.0. - Added in version 3.2.0.

View File

@ -17,6 +17,8 @@ header. See also the [macro overview page](../../features/macros.md).
- [**JSON_HAS_CPP_11**<br>**JSON_HAS_CPP_14**<br>**JSON_HAS_CPP_17**<br>**JSON_HAS_CPP_20**](json_has_cpp_11.md) - set supported C++ standard - [**JSON_HAS_CPP_11**<br>**JSON_HAS_CPP_14**<br>**JSON_HAS_CPP_17**<br>**JSON_HAS_CPP_20**](json_has_cpp_11.md) - set supported C++ standard
- [**JSON_HAS_FILESYSTEM**<br>**JSON_HAS_EXPERIMENTAL_FILESYSTEM**](json_has_filesystem.md) - control `std::filesystem` support - [**JSON_HAS_FILESYSTEM**<br>**JSON_HAS_EXPERIMENTAL_FILESYSTEM**](json_has_filesystem.md) - control `std::filesystem` support
- [**JSON_HAS_RANGES**](json_has_ranges.md) - control `std::ranges` support
- [**JSON_HAS_THREE_WAY_COMPARISON**](json_has_three_way_comparison.md) - control 3-way comparison support
- [**JSON_NO_IO**](json_no_io.md) - switch off functions relying on certain C++ I/O headers - [**JSON_NO_IO**](json_no_io.md) - switch off functions relying on certain C++ I/O headers
- [**JSON_SKIP_UNSUPPORTED_COMPILER_CHECK**](json_skip_unsupported_compiler_check.md) - do not warn about unsupported compilers - [**JSON_SKIP_UNSUPPORTED_COMPILER_CHECK**](json_skip_unsupported_compiler_check.md) - do not warn about unsupported compilers
@ -29,6 +31,12 @@ header. See also the [macro overview page](../../features/macros.md).
- [**JSON_USE_IMPLICIT_CONVERSIONS**](json_use_implicit_conversions.md) - control implicit conversions - [**JSON_USE_IMPLICIT_CONVERSIONS**](json_use_implicit_conversions.md) - control implicit conversions
<!-- comment-->
## Comparison behavior
- [**JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON**](json_use_legacy_discarded_value_comparison.md) -
control comparison of discarded values
## Serialization/deserialization macros ## Serialization/deserialization macros
- [**NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)**<br>**NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...)**](nlohmann_define_type_intrusive.md) - serialization/deserialization of types _with_ access to private variables - [**NLOHMANN_DEFINE_TYPE_INTRUSIVE(type, member...)**<br>**NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(type, member...)**](nlohmann_define_type_intrusive.md) - serialization/deserialization of types _with_ access to private variables

View File

@ -23,6 +23,19 @@ The default value is detected based on preprocessor macros such as `#!cpp __cplu
- `#!cpp JSON_HAS_CPP_11` is always defined. - `#!cpp JSON_HAS_CPP_11` is always defined.
- All macros are undefined outside the library. - All macros are undefined outside the library.
## Examples
??? example
The code below forces the library to use the C++14 standard:
```cpp
#define JSON_HAS_CPP_14 1
#include <nlohmann/json.hpp>
...
```
## Version history ## Version history
- Added in version 3.10.5. - Added in version 3.10.5.

View File

@ -25,6 +25,19 @@ The default value is detected based on the preprocessor macros `#!cpp __cpp_lib_
filesystem support. filesystem support.
- Both macros are undefined outside the library. - Both macros are undefined outside the library.
## Examples
??? example
The code below forces the library to use the header `<experimental/filesystem>`.
```cpp
#define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1
#include <nlohmann/json.hpp>
...
```
## Version history ## Version history
- Added in version 3.10.5. - Added in version 3.10.5.

View File

@ -0,0 +1,18 @@
# JSON_HAS_RANGES
```cpp
#define JSON_HAS_RANGES /* value */
```
This macro indicates whether the standard library has any support for ranges. Implies support for concepts.
Possible values are `1` when supported or `0` when unsupported.
## Default definition
The default value is detected based on the preprocessor macro `#!cpp __cpp_lib_ranges`.
When the macro is not defined, the library will define it to its default value.
## Version history
- Added in version 3.11.0.

View File

@ -0,0 +1,19 @@
# JSON_HAS_THREE_WAY_COMPARISON
```cpp
#define JSON_HAS_THREE_WAY_COMPARISON /* value */
```
This macro indicates whether the compiler and standard library support 3-way comparison.
Possible values are `1` when supported or `0` when unsupported.
## Default definition
The default value is detected based on the preprocessor macros `#!cpp __cpp_impl_three_way_comparison`
and `#!cpp __cpp_lib_three_way_comparison`.
When the macro is not defined, the library will define it to its default value.
## Version history
- Added in version 3.11.0.

View File

@ -16,6 +16,20 @@ By default, `#!cpp JSON_NO_IO` is not defined.
#undef JSON_NO_IO #undef JSON_NO_IO
``` ```
## Examples
??? example
The code below forces the library not to use the headers `<cstdio>`, `<ios>`, `<iosfwd>`, `<istream>`, and
`<ostream>`.
```cpp
#define JSON_NO_IO 1
#include <nlohmann/json.hpp>
...
```
## Version history ## Version history
- Added in version 3.10.0. - Added in version 3.10.0.

View File

@ -23,6 +23,19 @@ By default, the macro is not defined.
The explanatory [`what()`](https://en.cppreference.com/w/cpp/error/exception/what) string of exceptions is not The explanatory [`what()`](https://en.cppreference.com/w/cpp/error/exception/what) string of exceptions is not
available for MSVC if exceptions are disabled, see [#2824](https://github.com/nlohmann/json/discussions/2824). available for MSVC if exceptions are disabled, see [#2824](https://github.com/nlohmann/json/discussions/2824).
## Examples
??? example
The code below switches off exceptions in the library.
```cpp
#define JSON_NOEXCEPTION 1
#include <nlohmann/json.hpp>
...
```
## See also ## See also
- [Switch off exceptions](../../home/exceptions.md#switch-off-exceptions) for more information how to switch off exceptions - [Switch off exceptions](../../home/exceptions.md#switch-off-exceptions) for more information how to switch off exceptions

View File

@ -15,6 +15,19 @@ By default, the macro is not defined.
#undef JSON_SKIP_UNSUPPORTED_COMPILER_CHECK #undef JSON_SKIP_UNSUPPORTED_COMPILER_CHECK
``` ```
## Examples
??? example
The code below switches off the check whether the compiler is supported.
```cpp
#define JSON_SKIP_UNSUPPORTED_COMPILER_CHECK 1
#include <nlohmann/json.hpp>
...
```
## Version history ## Version history
Added in version 3.2.0. Added in version 3.2.0.

View File

@ -0,0 +1,61 @@
# JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON
```cpp
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON /* value */
```
This macro enables the (incorrect) legacy comparison behavior of discarded JSON values.
Possible values are `1` to enable or `0` to disable (default).
When enabled, comparisons involving at least one discarded JSON value yield results as follows:
| **Operator** | **Result** |
|--------------|---------------|
| `==` | `#!cpp false` |
| `!=` | `#!cpp true` |
| `<` | `#!cpp false` |
| `<=` | `#!cpp true` |
| `>=` | `#!cpp true` |
| `>` | `#!cpp false` |
Otherwise, comparisons involving at least one discarded JSON value always yield `#!cpp false`.
## Default definition
The default value is `0`.
```cpp
#define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0
```
When the macro is not defined, the library will define it to its default value.
## Notes
!!! warning "Inconsistent behavior in C++20 and beyond"
When targeting C++20 or above, enabling the legacy comparison behavior is _strongly_
discouraged.
- The 3-way comparison operator (`<=>`) will always give the correct result
(`#!cpp std::partial_ordering::unordered`) regardless of the value of
`JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON`.
- Overloads for the equality and relational operators emulate the legacy behavior.
Code outside your control may use either 3-way comparison or the equality and
relational operators, resulting in inconsistent and unpredictable behavior.
See [`operator<=>`](../basic_json/operator_spaceship.md) for more information on 3-way
comparison.
!!! warning "Deprecation"
The legacy comparison behavior is deprecated and may be removed in a future major
version release.
New code should not depend on it and existing code should try to remove or rewrite
expressions relying on it.
## Version history
- Added in version 3.11.0.

View File

@ -13,6 +13,23 @@ These macros are defined by the library and contain the version numbers accordin
The macros are defined according to the current library version. The macros are defined according to the current library version.
## Examples
??? example
The example below shows how `NLOHMANN_JSON_VERSION_MAJOR`, `NLOHMANN_JSON_VERSION_MINOR`, and
`NLOHMANN_JSON_VERSION_PATCH` are defined by the library.
```cpp
--8<-- "examples/nlohmann_json_version.cpp"
```
Output:
```json
--8<-- "examples/nlohmann_json_version.output"
```
## See also ## See also
- [meta](../basic_json/meta.md) - returns version information on the library - [meta](../basic_json/meta.md) - returns version information on the library

Some files were not shown because too many files have changed in this diff Show More