mirror of
https://github.com/nlohmann/json.git
synced 2026-10-01 14:15:50 +01:00
* Drop stale LCOV_EXCL_LINE from the json_pointer out_of_range.410 throw The comment said the size_type overflow check in array_index() is only triggered on special platforms like 32-bit, and the throw was excluded from coverage. On 64-bit platforms the check is true for SIZE_MAX itself, and unit-json_pointer.cpp has asserted that case four times since #5395, so the line is executed in the coverage job. Reword the comment and remove the exclusion marker so the coverage report notices if the tests stop reaching it. Part of #5725 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Name all three C-array check aliases in the enum-macro NOLINTs NLOHMANN_JSON_SERIALIZE_ENUM(_STRICT) suppressed the c-array warning under modernize-avoid-c-arrays only, but clang-tidy emits the same diagnostic under the aliases cppcoreguidelines-avoid-c-arrays and hicpp-avoid-c-arrays too. Any user running those checks got a false positive at every macro expansion, and our own tests needed a local NOLINT at each call site to work around it. Name all three aliases in the four macro comments instead, and drop the now-redundant c-array names from the five test call-site NOLINTs. Comment-only change; behavior, the public API, and the ABI do not change. Ran make amalgamate. Part of #5725 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Include doctest as a SYSTEM directory instead of disabling warnings for all tests test_main added -Wno-deprecated and -Wno-float-equal as PUBLIC compile options for every non-MSVC compiler, so they were applied to every translation unit, library headers included, and silenced the CI warnings meant to check the library's own -Wfloat-equal pragmas. The only code that actually needed the suppression was the vendored doctest.h, which was included as a normal (non-SYSTEM) directory. Include thirdparty/doctest as SYSTEM for test_main, matching what tests/abi/CMakeLists.txt already does, and drop the two suppressions from both targets. Verified locally that unit-comparison, unit-conversions and unit-constructor1 compile clean with -Werror -Weverything and doctest as -isystem, and that CMake still configures with JSON_BuildTests=ON. Part of #5725 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Remove the no-op ci_clang_analyze target ci_clang_analyze configured the build with the real compiler and only then wrapped ninja with scan-build. scan-build intercepts compiles by overriding CC/CXX, but build.ninja already had the compiler path baked in from the configure step, so every run bypassed the analyzer: CI logs show "No bugs found" after a normal build, never an analysis. The job also used Debian's frozen clang-tools-14 rather than the image's own clang, and CLANG_ANALYZER_CHECKS still named three valist.* checkers that current clang merged into security.VAList. ci_clang_tidy already runs every clang-analyzer-* check (via .clang-tidy's "Checks: '*'") with warnings as errors, so nothing is lost by removing the dead job. Delete ci_clang_analyze, CLANG_ANALYZER_CHECKS and the SCAN_BUILD_TOOL lookup from cmake/ci.cmake, drop it from the ubuntu.yml ci_static_analysis_clang matrix, and drop the now-unused clang-tools apt package (iwyu stays for ci_single_binaries). Reword quality_assurance.md and assurance_case.md, which described the dead job as a working control, to say the Clang Static Analyzer checks run through clang-tidy. Verified that `cmake -DJSON_CI=ON` still configures cleanly and that ci_clang_analyze no longer appears in the generated build or in any CMake/workflow file. Part of #5725 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Re-enable portability-template-virtual-member-function; remove redundant forwards .clang-tidy disabled three checks "to get the CI going" (#4489, 2024-11-13): portability-template-virtual-member-function, bugprone-use-after-move and its alias hicpp-invalid-access-moved. portability-template-virtual-member-function only flagged output_stream_adapter::write_character/write_characters; annotate both with NOLINT and re-enable the check. bugprone-use-after-move flagged several double forwards that have no effect at runtime: - from_json.hpp calls std::forward<BasicJsonType>(j).at(Idx) inside pack expansions; at() has no ref-qualified overloads and always returns an lvalue reference, so the forward is a no-op. Replace with plain j.at(Idx) in all four places. - the move constructor forwards the whole object to its base class and then reads other's members. That is item 9 of #5724 (together with its cppcheck suppressions) and is left to that change. - input_adapters.hpp forwards the container twice on purpose, so the begin/end iterator types match adapter_type; annotate with NOLINT and a comment instead of changing behavior. The check still flags the move constructor (see above) and two sites in at(KeyType&&) (both overloads, json.hpp, in the throw's string_t(std::forward<KeyType>(key)) after find(std::forward<KeyType>(key))). Open PR #5689 rewrites that hunk, so bugprone-use-after-move (and hicpp-invalid-access-moved) stay disabled for now, with a comment explaining why; re-enable them once #5689 and the #5724 move-constructor change have landed. Also resolve the portability-avoid-pragma-once TODO: single_include never has #pragma once (amalgamate.py strips it) and every supported compiler accepts it in include/, so keep it disabled with an explanatory comment instead of a TODO. Fix the stale "json.hpp, around line 1265" comment in unit-class_parser.cpp, which now points at the move constructor's actual line. Behavior, the public API and the ABI do not change. Verified with clang-tidy 22.1.8 that portability-template-virtual-member-function now reports nothing, that bugprone-use-after-move/ hicpp-invalid-access-moved report only the known at(KeyType&&) and move-constructor sites, and that unit-custom-base-class, unit-constructor1, unit-conversions, unit-element_access2, unit-class_parser and unit-diagnostic-positions (JSON_DIAGNOSTIC_POSITIONS=1) compile under ASan/UBSan and pass with the same assertion counts as before. Ran make amalgamate. Part of #5725 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Fix stale and malformed NOLINT comments json_sax.hpp named "-warnings-as-errors" in the NOLINT list on the two JSON_ASSERT(false) lines; that is the suffix clang-tidy appends to a diagnostic tag under WarningsAsErrors, not a check name, and every other JSON_ASSERT(false) omits it. unit-capacity.cpp carried 30 "// NOLINT(misc-const-correctness)" comments on "json j = ...;" declarations that are all used with non-const members afterwards, so the check has nothing to report there. unit-constructor2.cpp used a blanket "// NOLINT: access after move is OK here" on a use-after-move that hides every check on the line; naming bugprone-use-after-move and hicpp-invalid-access-moved keeps the intent once those checks are re-enabled (#5724). Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5725 item 10 * Remove stale .clang-tidy entries -google-runtime-references disabled a check that neither clang-tidy 22.1.8 nor 23.1.2 lists under --list-checks -checks='*'; it was removed upstream. The commented-out HeaderFilterRegex line has been unused since the active HeaderFilterRegex was introduced in #2561 (2021). Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5725 item 11 * Remove the GCC C++20 -Wignored-attributes pragma in json.hpp The pragma (added in #5164) claimed to work around the C++ modules redefinition errors of #5103, but #5103 is about hard errors (e.g. "redefinition of std::__is_constant_evaluated()", conflicting std::integral_constant) that ignoring a warning cannot suppress; they are traced to GCC PR 124430 and reproduce with <map> or <string> instead of json.hpp too. A GCC 16.2 -std=gnu++20 -fmodules build following #5103's repro steps still fails with the pragma in place, and a build of all test TUs with GCC_CXXFLAGS (which enable -Wignored-attributes) and the pragma removed produces no such warning. The block only hid a warning class from GCC C++20 users while suggesting #5103 was handled. Overlaps #5610, whose hunks touch the closing half of this pragma to insert the json_literals.hpp include. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5725 item 9 * Fix stale doxygen comments hidden by the -Wdocumentation pragma macro_scope.hpp ignores -Wdocumentation and -Wdocumentation-unknown-command for the whole library, which also hides genuine documentation mistakes: - detail::unescape() documented "@return unescaped string" but returns void and unescapes its argument in place; reworded to "@param[in,out] s string to unescape in place" and dropped the bogus @return. - basic_json::get()'s copy-conversion overload wrote "converted to @tparam ValueType" inside @return, which Doxygen and Clang parse as a second, malformed @tparam; changed to "@a ValueType", matching the two other get() overloads a few lines above that already use it. This narrows the gap the -Wdocumentation pragma needs to cover; fully replacing the Doxygen-only commands it also hides (item 2c) is left for after #5267. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5725 item 2 * Fix -Wextra-semi-stmt at its actual source, not assert() clang_flags.cmake blamed the global -Wno-extra-semi-stmt on assert(), but assert() expands to an expression under glibc and libc++ and does not trigger this warning. unit-assert_macro.cpp overrides JSON_ASSERT with "{if (!(x)) ++assert_counter; }", a bare block followed by a semicolon at every JSON_ASSERT(...) call site in the library; that was the actual source of 151 of the 208 -Wextra-semi-stmt sites found in a Clang 22 -Weverything sweep of the test suite with the flag removed. Switched to the standard do/while(false) macro idiom, which does not expand to a statement-plus-semicolon, and corrected the comment to name the remaining source instead: vendored Doctest's CAPTURE(x) shim, which already ends in a semicolon. Verified with clang++ -Wextra-semi-stmt (plus the file's other CI ignores) that unit-assert_macro.cpp now compiles without any -Wextra-semi-stmt diagnostic. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5725 item 8 (step 1 of 2; step 2 covers the CAPTURE() call sites) * Drop the redundant semicolon from CAPTURE() call sites; remove -Wno-extra-semi-stmt doctest_compatibility.h defines CAPTURE(x) as DOCTEST_CAPTURE(x); (with a trailing semicolon baked into the macro), specifically so call sites do not need to add one themselves; most of the ~267 call sites already follow that convention. The remaining 64 call sites across 20 files wrote "CAPTURE(x);" anyway, turning into a statement plus an empty statement and triggering -Wextra-semi-stmt. Dropped the redundant semicolon at each of those sites. With item 6 having already made vendored Doctest a SYSTEM include, and this the last known source of -Wextra-semi-stmt findings, removed the flag from clang_flags.cmake entirely. Verified with clang++ -Wextra-semi-stmt (plus the file's other CI ignores) that all 20 touched files, plus a file with no CAPTURE() use (unit-json_pointer.cpp), compile without any -Wextra-semi-stmt diagnostic. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5725 item 8 (step 2 of 2) * Switch ci_static_analysis_clang off the frozen LLVM 22 dev image ubuntu.yml pinned the clang-tidy/clang-tidy-sanitizer/single-binaries job to silkeh/clang:dev, a tag last pushed 2026-02-18 that reports "clang version 22.0.0 (...+20251015...)", a pre-release snapshot from before the LLVM 22 release; the maintainer now updates dev-unstable, 22, and latest instead. Switched to silkeh/clang:22, matching the other clang jobs on :latest. Verified with clang-tidy 22.1.8 (the image's actual version) against this repository's .clang-tidy and library headers what the release image newly reports compared to :dev: - readability-redundant-typename fires at ~250 sites across the _cpp20-relevant conversion/to_chars headers; the library targets C++11 and keeps the typenames, so the check is disabled in .clang-tidy, matching how the file already handles checks that don't fit a C++11 codebase. - misc-anonymous-namespace-in-header fires on the two anonymous namespaces in from_json.hpp and to_json.hpp; added the alias to their existing NOLINT (cert-dcl59-cpp, fuchsia-header-anon-namespaces, google-build-namespaces). - bugprone-std-namespace-modification fires on every addition to namespace std: the std::hash, std::formatter and std::swap overloads in json.hpp, and the std::tuple_size/std::tuple_element specializations in iteration_proxy.hpp (this last file is not named in #5725's item 5, found by actually running clang-tidy 22.1.8 against the current tree). All six are legal, deliberate additions to namespace std (explicit/partial specializations of std types, or the pre-C++20 std::swap overload); annotated each with the check name next to its existing cert-dcl58-cpp NOLINT. - modernize-avoid-c-style-cast reported nothing new. Also added clang++-22/21, clang-tidy-22/21, g++-16 and gcov-16 to the find_program search lists in ci.cmake so a local "maximal warnings" configure prefers the current toolchain version over an older one on PATH. #5725 item 5 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Regenerate cmake/gcc_flags.cmake for GCC 16.2.0 GCC_CXXFLAGS was generated for GCC 15.1.0, but ci_test_gcc and ci_test_gcc_cxx{11..26} now run in gcc:latest, currently GCC 16.2.0, so the "maximal warnings" job was missing warnings introduced since 15.1.0 while carrying entries GCC 16 treats as duplicates or no-ops. Regenerated with https://github.com/nlohmann/gcc_flags (patched locally to not crash on an option whose "-x c++ <opt> -" probe fails before it reads stdin, e.g. -Wabi=; the tool otherwise raises BrokenPipeError instead of recording the option as an error) run against g++ 16.2.0 in the official gcc:16 Docker image, keeping the documented -Wno-* exclusions and the same alphabetical placement scheme as before. Also added three GCC 16 warnings the generator cannot discover on its own because it only probes value ranges/lists it finds in the -Q option name itself, not in the enum choices --help=warnings documents separately: - -Wbidi-chars=any, -Wleading-whitespace=spaces: manually verified these compile cleanly with g++ 16.2.0. - -Wstrict-flex-arrays: deliberately NOT added, unlike the other two. Without -fstrict-flex-arrays (which the library does not enable, as it would change codegen for flexible array members), GCC prints "'-Wstrict-flex-arrays' is ignored when '-fstrict-flex-arrays' is not present" on every translation unit, and under our -Werror that note itself aborts the build. This differs from the harmless no-op warnings already kept in the file (-Whsa, -Wsynth, -Wunreachable-code, -Wunsafe-loop-optimizations), which emit nothing; #5725 item 7 named -Wstrict-flex-arrays as one of the flags GCC 16 adds, but did not anticipate this failure mode. Verified: compiled the library header and a representative set of test translation units (including ones touched by items 1, 3, 8, 9, 10 of this issue) with the regenerated GCC_CXXFLAGS plus -Werror under g++ 16.2.0 at -std=c++11 through -std=c++26, with zero warnings; ran the full local test suite (129/129 passing, unrelated to this compiler) as a regression check. CI must still confirm the actual ci_test_gcc / ci_test_standards_gcc targets end to end, since this was verified with direct g++ invocations rather than through the CMake/ CXXFLAGS environment-variable plumbing in ci.cmake. #5725 item 7 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Avoid std::basic_string<CharType> for non-character output_adapter CharType output_adapter<CharType, StringType> defaulted StringType to std::basic_string<CharType>, and (with JSON_NO_IO undefined) always declared a std::basic_ostream<CharType>&-taking constructor. For CharType with no non-deprecated std::char_traits specialization (only std::uint8_t is ever used this way, by the binary writers), simply naming either type - as an unused default template argument, or as an unused, never-called constructor's parameter type - instantiates std::char_traits<CharType> merely to name it, which some standard libraries mark deprecated: with the library-wide -Wdocumentation pragma (item 2's other half, left for a later commit) temporarily removed, an Apple clang 21 / libc++ TU calling json::to_cbor(j, vec) with std::vector<std::uint8_t>& got one -Wdeprecated-declarations warning per binary writer at the old output_adapters.hpp:193. Replaced the eager std::basic_string<CharType> / std::basic_ostream <CharType> defaults with a bool-tagged partial specialization (not std::conditional, which requires naming both branches' types up front regardless of which is selected, reproducing the same warning) that only ever names std::basic_string<CharType> / std::basic_ostream <CharType> when CharType is actually one of char, wchar_t, char16_t, char32_t, or (with __cpp_lib_char8_t) char8_t. For any other CharType, output_adapter's StringType and ostream-constructor parameter fall back to two distinct empty placeholder types, kept distinct so the two constructor overloads do not collide into a single redeclaration. Public API / behavior: passing a std::basic_string<std::uint8_t>& or std::basic_ostream<std::uint8_t>& directly to a binary writer's output_adapter now fails to compile instead of compiling with a deprecation warning; this was neither documented nor tested. All documented uses (std::vector<CharType>, std::basic_ostream<CharType> and StringType for character CharType) are unaffected. Verified with Apple clang 21 / libc++, with the two -Wdocumentation* "ignored" pragma lines in macro_scope.hpp temporarily removed and -std=c++11/c++20 plus the project's -Weverything flag set: calling to_cbor/to_msgpack/to_ubjson/to_bjdata/to_bson/to_bon8 on a std::vector<std::uint8_t> now produces no char_traits<unsigned char> (or any other) deprecation warning, while the char-based string- and ostream-adapter paths, and a to_cbor/from_cbor round trip, still compile and run correctly; also verified with GCC 16.2.0. Ran the full local test suite, including the binary-format unit tests (unit-cbor, unit-msgpack, unit-ubjson, unit-bjdata, unit-bson, unit-bon8, unit-binary_writer_sinks, unit-binary_formats, unit-custom-binary-type): 129/129 passing. #5725 item 2 (step a) Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Remove the library-wide -Wdocumentation pragma; fix what it hid macro_scope.hpp / macro_unscope.hpp pushed and popped a Clang diagnostic region over the entire library that ignored -Wdocumentation and -Wdocumentation-unknown-command. Removed both pragmas and fixed every finding a full -Wdocumentation (which implies -Wdocumentation-unknown-command and -Wdocumentation-deprecated-sync) build reports, so the library now compiles clean under Clang's documentation checks without a blanket suppression. Overlaps #5267, which is still open and edits a nearby doc block (json.hpp's get()/get_impl() @return, already fixed in the item 2 step (b) commit of this branch); this commit does not touch that block again. Unknown Doxygen alias commands (Doxyfile removed in #3071, so these were never rendered by anything) rewritten as plain prose, keeping the same information: - @requirement REQ-JSON-01 / REQ-JSON-02 (iter_impl.hpp, json_reverse_iterator.hpp): now "This class satisfies the following concept requirements (REQ-JSON-0N):". - @liveexample{prose,example-id} (three sites in json.hpp): kept the prose, dropped the command wrapper and the trailing example-id (docs/mkdocs/docs/examples/*.cpp still exist and are used directly by the rendered docs, not through this in-header alias) and unescaped the "\," commas that were only needed for the old alias's comma-separated argument syntax. - @complexity X (json.hpp x4, json_pointer.hpp x2, serializer.hpp x1): now "Complexity: X". Backslash sequences Clang's comment lexer tried to parse as commands, escaped to render as literal backslashes: - lexer.hpp get_codepoint(): two `\u` occurrences. - binary_reader.hpp get_bson_cstr() / get_bson_cstr_bulk(): two `\x00` occurrences. - serializer.hpp: three `\uXXXX` occurrences (constructor @param, append_codepoint_to_string_buffer() @brief, and the ensure_ascii member comment). One finding remained after all of the above: Clang reports "declaration is marked with '@deprecated' command but does not have a deprecation attribute" on the deprecated sax_parse(span_input_adapter&&, ...) overload, even though JSON_HEDLEY_DEPRECATED_FOR does expand to __attribute__((deprecated(...))) for Clang. Several isolated reproductions of this exact declaration shape - doc comment, template<>, two stacked __attribute__ macros, an overload set sharing the name - did not reproduce the warning, so this looks like a Clang comment/declaration-association quirk specific to this overload inside the much larger basic_json class template, not an actual documentation defect. Rather than keep the pragma library-wide for one Clang false positive, added a tightly scoped -Wdocumentation-deprecated-sync push/pop around just that overload. Verified with Apple clang 21 and the project's actual -Weverything flag set (cmake/clang_flags.cmake) on the full header at -std=c++11 and -std=c++20: zero -Wdocumentation* diagnostics. Also compiled clean with GCC 16.2.0 (the pragmas are already __clang__-gated, so this only confirms no unrelated breakage). Ran make check-amalgamation and the full local test suite: 129/129 passing. #5725 item 2 (step c) Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Take the JSON value by const reference in the array and tuple from_json paths Review feedback on #5737 (gregmarr): once the no-op std::forward calls are gone, the forwarding references have no purpose. from_json_fn passes the value as const BasicJsonType&, so these functions were only ever instantiated with a const lvalue anyway. The std::array, std::pair and std::tuple overloads of from_json and their helpers now take const BasicJsonType& and pass j on unchanged. Because the deduced BasicJsonType is now the plain type, tuple_type and the static_assert name const BasicJsonType& explicitly, so the reference checks are unchanged: get<std::tuple<const std::string&>>() still works, and get<std::tuple<std::string&>>() still fails the same static_assert. from_json_tuple_get_impl keeps its forwarding reference, since tuple_type calls it through std::declval. Behavior, the public API and the ABI do not change. unit-conversions, unit-constructor1, unit-udt, unit-udt_macro, unit-regression1/2/3, unit-deserialization, unit-noexcept, unit-items, unit-allocator, unit-custom-object-type, unit-ordered_json2 and unit-brace-init-copy-semantics pass at C++11, C++17 and C++20 with unchanged assertion counts. Ran make amalgamate. Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me>
649 lines
24 KiB
C++
649 lines
24 KiB
C++
// __ _____ _____ _____
|
|
// __| | __| | | | JSON for Modern C++
|
|
// | | |__ | | | | | | version 3.12.0
|
|
// |_____|_____|_____|_|___| https://github.com/nlohmann/json
|
|
//
|
|
// SPDX-FileCopyrightText: 2013-2026 Niels Lohmann <https://nlohmann.me>
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
#pragma once
|
|
|
|
#include <algorithm> // transform
|
|
#include <array> // array
|
|
#include <forward_list> // forward_list
|
|
#include <iterator> // inserter, front_inserter, end
|
|
#include <map> // map
|
|
#include <string> // string
|
|
#include <tuple> // tuple, make_tuple
|
|
#include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible
|
|
#include <unordered_map> // unordered_map
|
|
#include <utility> // pair, declval
|
|
#include <valarray> // valarray
|
|
#include <vector> // vector
|
|
|
|
#include <nlohmann/detail/exceptions.hpp>
|
|
#include <nlohmann/detail/macro_scope.hpp>
|
|
#include <nlohmann/detail/meta/cpp_future.hpp>
|
|
#include <nlohmann/detail/meta/identity_tag.hpp>
|
|
#include <nlohmann/detail/meta/std_fs.hpp>
|
|
#include <nlohmann/detail/meta/type_traits.hpp>
|
|
#include <nlohmann/detail/meta/logic.hpp>
|
|
#include <nlohmann/detail/string_concat.hpp>
|
|
#include <nlohmann/detail/value_t.hpp>
|
|
|
|
// include after macro_scope.hpp
|
|
#ifdef JSON_HAS_CPP_17
|
|
#include <optional> // optional
|
|
#endif
|
|
|
|
#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM
|
|
#include <string_view> // u8string_view
|
|
#endif
|
|
|
|
NLOHMANN_JSON_NAMESPACE_BEGIN
|
|
namespace detail
|
|
{
|
|
|
|
template<typename BasicJsonType>
|
|
inline void from_json(const BasicJsonType& j, typename std::nullptr_t& n)
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!j.is_null()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be null, but is ", j.type_name()), &j));
|
|
}
|
|
n = nullptr;
|
|
}
|
|
|
|
#ifdef JSON_HAS_CPP_17
|
|
template < typename BasicJsonType, typename T,
|
|
typename std::enable_if < !nlohmann::detail::is_basic_json<T>::value, int >::type = 0 >
|
|
void from_json(const BasicJsonType& j, std::optional<T>& opt)
|
|
{
|
|
if (j.is_null())
|
|
{
|
|
opt = std::nullopt;
|
|
}
|
|
else
|
|
{
|
|
opt.emplace(j.template get<T>());
|
|
}
|
|
}
|
|
#endif // JSON_HAS_CPP_17
|
|
|
|
// overloads for basic_json template parameters
|
|
template < typename BasicJsonType, typename ArithmeticType,
|
|
enable_if_t < std::is_arithmetic<ArithmeticType>::value&&
|
|
!std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
|
|
int > = 0 >
|
|
void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
|
|
{
|
|
switch (static_cast<value_t>(j))
|
|
{
|
|
case value_t::number_unsigned:
|
|
{
|
|
val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
|
|
break;
|
|
}
|
|
case value_t::number_integer:
|
|
{
|
|
val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
|
|
break;
|
|
}
|
|
case value_t::number_float:
|
|
{
|
|
val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
|
|
break;
|
|
}
|
|
|
|
case value_t::null:
|
|
case value_t::object:
|
|
case value_t::array:
|
|
case value_t::string:
|
|
case value_t::boolean:
|
|
case value_t::binary:
|
|
case value_t::discarded:
|
|
default:
|
|
JSON_THROW(type_error::create(302, concat("type must be number, but is ", j.type_name()), &j));
|
|
}
|
|
}
|
|
|
|
template<typename BasicJsonType>
|
|
inline void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!j.is_boolean()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be boolean, but is ", j.type_name()), &j));
|
|
}
|
|
b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
|
|
}
|
|
|
|
template<typename BasicJsonType>
|
|
inline void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be string, but is ", j.type_name()), &j));
|
|
}
|
|
s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
|
|
}
|
|
|
|
template <
|
|
typename BasicJsonType, typename StringType,
|
|
enable_if_t <
|
|
std::is_assignable<StringType&, const typename BasicJsonType::string_t>::value
|
|
&& is_detected_exact<typename BasicJsonType::string_t::value_type, value_type_t, StringType>::value
|
|
&& !std::is_same<typename BasicJsonType::string_t, StringType>::value
|
|
&& !is_json_ref<StringType>::value, int > = 0 >
|
|
inline void from_json(const BasicJsonType& j, StringType& s)
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be string, but is ", j.type_name()), &j));
|
|
}
|
|
|
|
s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
|
|
}
|
|
|
|
template<typename BasicJsonType>
|
|
inline void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
|
|
{
|
|
get_arithmetic_value(j, val);
|
|
}
|
|
|
|
template<typename BasicJsonType>
|
|
inline void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
|
|
{
|
|
get_arithmetic_value(j, val);
|
|
}
|
|
|
|
template<typename BasicJsonType>
|
|
inline void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
|
|
{
|
|
get_arithmetic_value(j, val);
|
|
}
|
|
|
|
#if !JSON_DISABLE_ENUM_SERIALIZATION
|
|
template<typename BasicJsonType, typename EnumType,
|
|
enable_if_t<std::is_enum<EnumType>::value, int> = 0>
|
|
inline void from_json(const BasicJsonType& j, EnumType& e)
|
|
{
|
|
using underlying_type = typename std::underlying_type<EnumType>::type;
|
|
// get_arithmetic_value() does not accept boolean_t; read the number that to_json() wrote instead
|
|
using value_type = typename std::conditional<std::is_same<underlying_type, typename BasicJsonType::boolean_t>::value,
|
|
typename BasicJsonType::number_unsigned_t, underlying_type>::type;
|
|
value_type val;
|
|
get_arithmetic_value(j, val);
|
|
e = static_cast<EnumType>(static_cast<underlying_type>(val));
|
|
}
|
|
#endif // JSON_DISABLE_ENUM_SERIALIZATION
|
|
|
|
// forward_list doesn't have an insert method
|
|
template<typename BasicJsonType, typename T, typename Allocator,
|
|
enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
|
|
inline void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
|
}
|
|
l.clear();
|
|
std::transform(j.rbegin(), j.rend(),
|
|
std::front_inserter(l), [](const BasicJsonType & i)
|
|
{
|
|
return i.template get<T>();
|
|
});
|
|
}
|
|
|
|
// valarray doesn't have an insert method
|
|
template<typename BasicJsonType, typename T,
|
|
enable_if_t<is_getable<BasicJsonType, T>::value, int> = 0>
|
|
inline void from_json(const BasicJsonType& j, std::valarray<T>& l)
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
|
}
|
|
l.resize(j.size());
|
|
std::transform(j.begin(), j.end(), std::begin(l),
|
|
[](const BasicJsonType & elem)
|
|
{
|
|
return elem.template get<T>();
|
|
});
|
|
}
|
|
|
|
template<typename BasicJsonType, typename T, std::size_t N>
|
|
auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
|
-> decltype(j.template get<T>(), void())
|
|
{
|
|
for (std::size_t i = 0; i < N; ++i)
|
|
{
|
|
arr[i] = j.at(i).template get<T>();
|
|
}
|
|
}
|
|
|
|
template<typename BasicJsonType, typename T, std::size_t N1, std::size_t N2>
|
|
auto from_json(const BasicJsonType& j, T (&arr)[N1][N2]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
|
-> decltype(j.template get<T>(), void())
|
|
{
|
|
for (std::size_t i1 = 0; i1 < N1; ++i1)
|
|
{
|
|
for (std::size_t i2 = 0; i2 < N2; ++i2)
|
|
{
|
|
arr[i1][i2] = j.at(i1).at(i2).template get<T>();
|
|
}
|
|
}
|
|
}
|
|
|
|
template<typename BasicJsonType, typename T, std::size_t N1, std::size_t N2, std::size_t N3>
|
|
auto from_json(const BasicJsonType& j, T (&arr)[N1][N2][N3]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
|
-> decltype(j.template get<T>(), void())
|
|
{
|
|
for (std::size_t i1 = 0; i1 < N1; ++i1)
|
|
{
|
|
for (std::size_t i2 = 0; i2 < N2; ++i2)
|
|
{
|
|
for (std::size_t i3 = 0; i3 < N3; ++i3)
|
|
{
|
|
arr[i1][i2][i3] = j.at(i1).at(i2).at(i3).template get<T>();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
template<typename BasicJsonType, typename T, std::size_t N1, std::size_t N2, std::size_t N3, std::size_t N4>
|
|
auto from_json(const BasicJsonType& j, T (&arr)[N1][N2][N3][N4]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
|
-> decltype(j.template get<T>(), void())
|
|
{
|
|
for (std::size_t i1 = 0; i1 < N1; ++i1)
|
|
{
|
|
for (std::size_t i2 = 0; i2 < N2; ++i2)
|
|
{
|
|
for (std::size_t i3 = 0; i3 < N3; ++i3)
|
|
{
|
|
for (std::size_t i4 = 0; i4 < N4; ++i4)
|
|
{
|
|
arr[i1][i2][i3][i4] = j.at(i1).at(i2).at(i3).at(i4).template get<T>();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
template<typename BasicJsonType>
|
|
inline void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/)
|
|
{
|
|
arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
|
|
}
|
|
|
|
template<typename BasicJsonType, typename T, std::size_t N>
|
|
auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr,
|
|
priority_tag<2> /*unused*/)
|
|
-> decltype(j.template get<T>(), void())
|
|
{
|
|
for (std::size_t i = 0; i < N; ++i)
|
|
{
|
|
arr[i] = j.at(i).template get<T>();
|
|
}
|
|
}
|
|
|
|
template<typename BasicJsonType, typename ConstructibleArrayType,
|
|
enable_if_t<
|
|
std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value,
|
|
int> = 0>
|
|
auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/)
|
|
-> decltype(
|
|
arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()),
|
|
j.template get<typename ConstructibleArrayType::value_type>(),
|
|
void())
|
|
{
|
|
using std::end;
|
|
|
|
ConstructibleArrayType ret;
|
|
ret.reserve(j.size());
|
|
std::transform(j.begin(), j.end(),
|
|
std::inserter(ret, end(ret)), [](const BasicJsonType & i)
|
|
{
|
|
// get<BasicJsonType>() returns *this, this won't call a from_json
|
|
// method when value_type is BasicJsonType
|
|
return i.template get<typename ConstructibleArrayType::value_type>();
|
|
});
|
|
arr = std::move(ret);
|
|
}
|
|
|
|
template<typename BasicJsonType, typename ConstructibleArrayType,
|
|
enable_if_t<
|
|
std::is_assignable<ConstructibleArrayType&, ConstructibleArrayType>::value,
|
|
int> = 0>
|
|
inline void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr,
|
|
priority_tag<0> /*unused*/)
|
|
{
|
|
using std::end;
|
|
|
|
ConstructibleArrayType ret;
|
|
std::transform(
|
|
j.begin(), j.end(), std::inserter(ret, end(ret)),
|
|
[](const BasicJsonType & i)
|
|
{
|
|
// get<BasicJsonType>() returns *this, this won't call a from_json
|
|
// method when value_type is BasicJsonType
|
|
return i.template get<typename ConstructibleArrayType::value_type>();
|
|
});
|
|
arr = std::move(ret);
|
|
}
|
|
|
|
template < typename BasicJsonType, typename ConstructibleArrayType,
|
|
enable_if_t <
|
|
is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value&&
|
|
!is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value&&
|
|
!is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value&&
|
|
!std::is_same<ConstructibleArrayType, typename BasicJsonType::binary_t>::value&&
|
|
!is_compatible_binary_type<BasicJsonType, ConstructibleArrayType>::value&&
|
|
!is_basic_json<ConstructibleArrayType>::value,
|
|
int > = 0 >
|
|
auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr)
|
|
-> decltype(from_json_array_impl(j, arr, priority_tag<3> {}),
|
|
j.template get<typename ConstructibleArrayType::value_type>(),
|
|
void())
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
|
}
|
|
|
|
from_json_array_impl(j, arr, priority_tag<3> {});
|
|
}
|
|
|
|
template < typename BasicJsonType, typename T, std::size_t... Idx >
|
|
std::array<T, sizeof...(Idx)> from_json_inplace_array_impl(const BasicJsonType& j,
|
|
identity_tag<std::array<T, sizeof...(Idx)>> /*unused*/, index_sequence<Idx...> /*unused*/)
|
|
{
|
|
return { { j.at(Idx).template get<T>()... } };
|
|
}
|
|
|
|
template < typename BasicJsonType, typename T, std::size_t N >
|
|
auto from_json(const BasicJsonType& j, identity_tag<std::array<T, N>> tag)
|
|
-> decltype(from_json_inplace_array_impl(j, tag, make_index_sequence<N> {}))
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
|
}
|
|
|
|
return from_json_inplace_array_impl(j, tag, make_index_sequence<N> {});
|
|
}
|
|
|
|
template<typename BasicJsonType>
|
|
inline void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin)
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!j.is_binary()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be binary, but is ", j.type_name()), &j));
|
|
}
|
|
|
|
bin = *j.template get_ptr<const typename BasicJsonType::binary_t*>();
|
|
}
|
|
|
|
template < typename BasicJsonType, typename CompatibleArrayType,
|
|
enable_if_t < is_compatible_binary_type<BasicJsonType, CompatibleArrayType>::value,
|
|
int > = 0 >
|
|
inline void from_json(const BasicJsonType& j, CompatibleArrayType& bin)
|
|
{
|
|
if (j.is_binary())
|
|
{
|
|
bin = static_cast<CompatibleArrayType>(*j.template get_ptr<const typename BasicJsonType::binary_t*>());
|
|
}
|
|
else if (j.is_array())
|
|
{
|
|
from_json_array_impl(j, bin, priority_tag<3> {});
|
|
}
|
|
else
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be binary or array, but is ", j.type_name()), &j));
|
|
}
|
|
}
|
|
|
|
template<typename ConstructibleObjectType>
|
|
auto from_json_object_reserve(ConstructibleObjectType& obj, typename ConstructibleObjectType::size_type size, priority_tag<1> /*unused*/)
|
|
-> decltype(obj.reserve(size), void())
|
|
{
|
|
obj.reserve(size);
|
|
}
|
|
|
|
template<typename ConstructibleObjectType>
|
|
inline void from_json_object_reserve(ConstructibleObjectType& /*obj*/, std::size_t /*size*/, priority_tag<0> /*unused*/)
|
|
{}
|
|
|
|
template<typename BasicJsonType, typename ConstructibleObjectType,
|
|
enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0>
|
|
inline void from_json(const BasicJsonType& j, ConstructibleObjectType& obj)
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!j.is_object()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be object, but is ", j.type_name()), &j));
|
|
}
|
|
|
|
ConstructibleObjectType ret;
|
|
const auto* inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
|
|
from_json_object_reserve(ret, inner_object->size(), priority_tag<1> {});
|
|
for (const auto& p : *inner_object)
|
|
{
|
|
ret.emplace(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>());
|
|
}
|
|
obj = std::move(ret);
|
|
}
|
|
|
|
// overload for arithmetic types, not chosen for basic_json template arguments
|
|
// (BooleanType, etc.); note: Is it really necessary to provide explicit
|
|
// overloads for boolean_t etc. in case of a custom BooleanType which is not
|
|
// an arithmetic type?
|
|
template < typename BasicJsonType, typename ArithmeticType,
|
|
enable_if_t <
|
|
std::is_arithmetic<ArithmeticType>::value&&
|
|
!std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value&&
|
|
!std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value&&
|
|
!std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value&&
|
|
!std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
|
|
int > = 0 >
|
|
inline void from_json(const BasicJsonType& j, ArithmeticType& val)
|
|
{
|
|
switch (static_cast<value_t>(j))
|
|
{
|
|
case value_t::number_unsigned:
|
|
{
|
|
val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
|
|
break;
|
|
}
|
|
case value_t::number_integer:
|
|
{
|
|
val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
|
|
break;
|
|
}
|
|
case value_t::number_float:
|
|
{
|
|
val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
|
|
break;
|
|
}
|
|
case value_t::boolean:
|
|
{
|
|
val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
|
|
break;
|
|
}
|
|
|
|
case value_t::null:
|
|
case value_t::object:
|
|
case value_t::array:
|
|
case value_t::string:
|
|
case value_t::binary:
|
|
case value_t::discarded:
|
|
default:
|
|
JSON_THROW(type_error::create(302, concat("type must be number, but is ", j.type_name()), &j));
|
|
}
|
|
}
|
|
|
|
template<typename BasicJsonType, typename Type>
|
|
detail::uncvref_t<Type> from_json_tuple_get_impl(BasicJsonType&& j, detail::identity_tag<Type> /*unused*/, detail::priority_tag<0> /*unused*/)
|
|
{
|
|
return std::forward<BasicJsonType>(j).template get<detail::uncvref_t<Type>>();
|
|
}
|
|
|
|
template<typename BasicJsonType, typename Type,
|
|
detail::enable_if_t<detail::is_compatible_reference_type<BasicJsonType, Type>::value, int> = 0>
|
|
Type from_json_tuple_get_impl(BasicJsonType && j, detail::identity_tag<Type> /*unused*/, detail::priority_tag<1> /*unused*/)
|
|
{
|
|
return std::forward<BasicJsonType>(j).template get_ref<Type>();
|
|
}
|
|
|
|
template<typename BasicJsonType, typename Type,
|
|
detail::enable_if_t<std::is_arithmetic<uncvref_t<Type>>::value, int> = 0>
|
|
detail::uncvref_t<Type> from_json_tuple_get_impl(BasicJsonType && j, detail::identity_tag<Type> /*unused*/, detail::priority_tag<2> /*unused*/)
|
|
{
|
|
return std::forward<BasicJsonType>(j).template get<detail::uncvref_t<Type>>();
|
|
}
|
|
|
|
template<std::size_t PTagValue, typename BasicJsonType, typename... Types>
|
|
using tuple_type = std::tuple < decltype(from_json_tuple_get_impl(std::declval<BasicJsonType>(), detail::identity_tag<Types> {}, detail::priority_tag<PTagValue> {}))... >;
|
|
|
|
template<std::size_t PTagValue, typename... Args, typename BasicJsonType, std::size_t... Idx>
|
|
tuple_type<PTagValue, const BasicJsonType&, Args...> from_json_tuple_impl_base(const BasicJsonType& j, index_sequence<Idx...> /*unused*/)
|
|
{
|
|
return tuple_type<PTagValue, const BasicJsonType&, Args...>(from_json_tuple_get_impl(j.at(Idx), detail::identity_tag<Args> {}, detail::priority_tag<PTagValue> {})...);
|
|
}
|
|
|
|
template<std::size_t PTagValue, typename BasicJsonType>
|
|
std::tuple<> from_json_tuple_impl_base(const BasicJsonType& /*unused*/, index_sequence<> /*unused*/)
|
|
{
|
|
return {};
|
|
}
|
|
|
|
template < typename BasicJsonType, class A1, class A2 >
|
|
std::pair<A1, A2> from_json_tuple_impl(const BasicJsonType& j, identity_tag<std::pair<A1, A2>> /*unused*/, priority_tag<0> /*unused*/)
|
|
{
|
|
return {j.at(0).template get<A1>(),
|
|
j.at(1).template get<A2>()};
|
|
}
|
|
|
|
template<typename BasicJsonType, typename A1, typename A2>
|
|
inline void from_json_tuple_impl(const BasicJsonType& j, std::pair<A1, A2>& p, priority_tag<1> /*unused*/)
|
|
{
|
|
p = from_json_tuple_impl(j, identity_tag<std::pair<A1, A2>> {}, priority_tag<0> {});
|
|
}
|
|
|
|
template<typename BasicJsonType, typename... Args>
|
|
std::tuple<Args...> from_json_tuple_impl(const BasicJsonType& j, identity_tag<std::tuple<Args...>> /*unused*/, priority_tag<2> /*unused*/)
|
|
{
|
|
static_assert(cxpr_and<cxpr_or<cxpr_not<std::is_reference<Args>>, is_compatible_reference_type<const BasicJsonType&, Args>>...>::value,
|
|
"Can not return a tuple containing references to types not contained in a Json, try Json::get_to()");
|
|
return from_json_tuple_impl_base<1, Args...>(j, index_sequence_for<Args...> {});
|
|
}
|
|
|
|
template<typename BasicJsonType, typename... Args>
|
|
inline void from_json_tuple_impl(const BasicJsonType& j, std::tuple<Args...>& t, priority_tag<3> /*unused*/)
|
|
{
|
|
t = from_json_tuple_impl_base<2, Args...>(j, index_sequence_for<Args...> {});
|
|
}
|
|
|
|
template<typename BasicJsonType, typename TupleRelated>
|
|
auto from_json(const BasicJsonType& j, TupleRelated&& t)
|
|
-> decltype(from_json_tuple_impl(j, std::forward<TupleRelated>(t), priority_tag<3> {}))
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
|
}
|
|
|
|
return from_json_tuple_impl(j, std::forward<TupleRelated>(t), priority_tag<3> {});
|
|
}
|
|
|
|
template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
|
|
typename = enable_if_t < !std::is_constructible <
|
|
typename BasicJsonType::string_t, Key >::value >>
|
|
inline void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
|
}
|
|
m.clear();
|
|
for (const auto& p : j)
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be array, but is ", p.type_name()), &p));
|
|
}
|
|
m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
|
|
}
|
|
}
|
|
|
|
template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator,
|
|
typename = enable_if_t < !std::is_constructible <
|
|
typename BasicJsonType::string_t, Key >::value >>
|
|
inline void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!j.is_array()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j));
|
|
}
|
|
m.clear();
|
|
for (const auto& p : j)
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!p.is_array()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be array, but is ", p.type_name()), &p));
|
|
}
|
|
m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>());
|
|
}
|
|
}
|
|
|
|
#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM
|
|
|
|
// Workaround for MSVC 19.51 (and possibly later): in large in large cpp files, the compiler may fail to resolve with generic has_from_json (issue #4996)
|
|
template<typename BasicJsonType>
|
|
struct has_from_json<BasicJsonType, std_fs::path, void> : std::true_type {};
|
|
|
|
template<typename BasicJsonType>
|
|
inline void from_json(const BasicJsonType& j, std_fs::path& p)
|
|
{
|
|
if (JSON_HEDLEY_UNLIKELY(!j.is_string()))
|
|
{
|
|
JSON_THROW(type_error::create(302, concat("type must be string, but is ", j.type_name()), &j));
|
|
}
|
|
const auto& s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
|
|
// Checking for C++20 standard or later can be insufficient in case the
|
|
// library support for char8_t is either incomplete or was disabled
|
|
// altogether. Use the __cpp_lib_char8_t feature test instead.
|
|
#if defined(__cpp_lib_char8_t) && (__cpp_lib_char8_t >= 201907L)
|
|
p = std_fs::path(std::u8string_view(reinterpret_cast<const char8_t*>(s.data()), s.size()));
|
|
#else
|
|
p = std_fs::u8path(s); // accepts UTF-8 encoded std::string in C++17, deprecated in C++20
|
|
#endif
|
|
}
|
|
#endif
|
|
|
|
struct from_json_fn
|
|
{
|
|
template<typename BasicJsonType, typename T>
|
|
auto operator()(const BasicJsonType& j, T&& val) const
|
|
noexcept(noexcept(from_json(j, std::forward<T>(val))))
|
|
-> decltype(from_json(j, std::forward<T>(val)))
|
|
{
|
|
return from_json(j, std::forward<T>(val));
|
|
}
|
|
};
|
|
|
|
} // namespace detail
|
|
|
|
#ifndef JSON_HAS_CPP_17
|
|
/// namespace to hold default `from_json` function
|
|
/// to see why this is required:
|
|
/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html
|
|
namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces,misc-anonymous-namespace-in-header)
|
|
{
|
|
#endif
|
|
JSON_INLINE_VARIABLE constexpr const auto& from_json = // NOLINT(misc-definitions-in-headers)
|
|
detail::static_const<detail::from_json_fn>::value;
|
|
#ifndef JSON_HAS_CPP_17
|
|
} // namespace
|
|
#endif
|
|
|
|
NLOHMANN_JSON_NAMESPACE_END
|