mirror of
https://github.com/nlohmann/json.git
synced 2026-10-04 13:40:33 +00:00
* Remove unused is_sax and is_detected_convertible detail::is_sax had no user: the parser and the binary reader only use is_sax_static_asserts, so is_sax was a second, unchecked copy of the SAX event list. is_sax_static_asserts asserted boolean(bool) twice in a row, and detail::is_detected_convertible was never used anywhere. Remove all three and include <cstddef> for size_t instead of <cstdint>. Only names in nlohmann::detail are removed; behavior, public API and ABI are unchanged. The diagnostics for an incomplete SAX handler are the same, apart from the duplicated boolean() message. Part of #5708 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Replace meta/logic.hpp with a disjunction trait meta/logic.hpp added a second set of type-level boolean helpers (cxpr_and, cxpr_or, cxpr_not, ...) next to the existing conjunction and negation in type_traits.hpp. It was used only by one static_assert in from_json_tuple_impl, two of its templates were never used, and it was the only header without the license banner and relied on transitive includes for <type_traits>. Add the missing disjunction next to conjunction and negation, use the three in the static_assert, and delete logic.hpp together with its BUILD.bazel entry. same_sign now uses disjunction as well, which resolves the 2022 TODO waiting for such a trait. The static_assert accepts and rejects the same types as before. Only names in nlohmann::detail change; behavior, public API and ABI are unchanged. Part of #5708 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Remove unused would_call_std_* from NLOHMANN_CAN_CALL_STD_FUNC_IMPL Besides detail::result_of_begin/end, which is_range and iterator_t use, the macro defined a namespace detail2 with a tag type, a catch-all overload and would_call_std_begin/end, plus would_call_std_begin/end structs directly in namespace nlohmann. Nothing has used them since they were added in #3020. Reduce the macro to its detail part. Without the trailing struct the ';' after the two invocations would be an empty declaration that -Wextra-semi flags, so drop it. macro_scope.hpp included meta/detected.hpp only for this macro; all users of detected.hpp include it (or type_traits.hpp) themselves, so remove the include. Behavior and ABI are unchanged. The undocumented, untested and unused names nlohmann::would_call_std_begin, nlohmann::would_call_std_end and namespace nlohmann::detail2 are no longer declared. Part of #5708 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Simplify is_ordered_map to reuse has_capacity is_ordered_map re-detected capacity() with a C++03 sizeof/vararg trick right after has_capacity did the same detection through is_detected. For ordered_map, the old trick took the address of std::vector::capacity, which [namespace.std]/6 makes unspecified. Reuse has_capacity instead, which removes the unspecified-behavior pointer-to-std-member and two NOLINT suppressions. Part of #5708 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Remove duplicate const overload of json_pointer::get_checked The const and non-const get_checked() overloads had byte-identical 50-line bodies, differing only in the signature. The remaining template deduces a const-qualified BasicJsonType for const callers, so at(), the out_of_range::create() calls and the bounds check all still work. Part of #5708 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Fix tautological clause in iter_impl's iterator category assertion The static_assert meant to check the LegacyBidirectionalIterator named requirement had a first clause comparing std::bidirectional_iterator_tag to itself, which is always true and checks nothing; only array_t::iterator was actually being checked, despite the message claiming object iterators were checked too. Drop the tautological clause, reword the message to describe what is actually checked, and note that object_t may use a forward-only iterator as long as reverse iteration and operator-- are unused. The check is intentionally not extended to object_t::iterator, since that would reject object types with forward-only iterators that compile and work correctly today. Part of #5708 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Fix misplaced and stale comments in JSON_HAS_RANGES and conversions The JSON_HAS_RANGES feature-detection block had its libc++ comment sitting above the clang+libstdc++ branch it does not describe, leaving the libc++ branch uncommented and the clang+libstdc++ branch without its own rationale. Move each comment to sit under its own branch, and give the clang+libstdc++ branch (added in issue 5161) its own one-line reason referencing that issue instead of reusing the libc++ branch's comment. Also fix a duplicated-word typo ("in large in large cpp files") in from_json.hpp, drop two unanswered 2017 design questions left as comments in type_traits.hpp and from_json.hpp that no longer reflect open questions, and correct NLOHMANN_JSON_SERIALIZE_ENUM_STRICT's @since tag from 3.12.0 to 3.13.0, the release it was actually introduced in. Part of #5708 Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Support any-rank C arrays in from_json, not just rank 1-4 from_json() for C arrays had four hand-unrolled overloads (rank 1-4, added incrementally in #4262), each with its own nested loops. to_json() already handles any rank recursively, so a rank-5+ C array could be serialized but not read back with get_to()/get<>(). Replace the four overloads with one from_json() SFINAE-constrained on get<remove_all_extents<T>::type>() existing, forwarding to a pair of mutually recursive from_json_c_array_element() helpers: one assigns a non-array element via get<T>(), the other loops over a array element and recurses one dimension at a time. Each dimension still goes through at(), so type_error.304/out_of_range.401 stay unchanged; ranks 1-4 keep their existing behavior and semantics. Adds rank-5 round-trip and mismatched-shape tests to unit-conversions.cpp. Public API: additive only (rank 5+ C arrays become readable). Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5708 item 1 * Move templated_json_throw into nlohmann::detail templated_json_throw() was defined in macro_scope.hpp, which is included outside NLOHMANN_JSON_NAMESPACE_BEGIN, so the helper leaked into the global namespace as ::templated_json_throw with no ABI tag. Unqualified lookup in NLOHMANN_JSON_SERIALIZE_ENUM_STRICT could then bind to a same-named function declared in the user's own namespace instead, which fails to compile with Clang ("does not name a template"). Move the helper next to the exception classes in exceptions.hpp, inside nlohmann::detail, and call it qualified as ::nlohmann::detail::templated_json_throw<...>(...) from both macro expansion sites. Rewrite the doc comment to give the real reason for the helper (JSON_THROW may expand to code that discards its argument, e.g. when exceptions are disabled) and fix the "supress" typo. templated_json_throw was never released (added by #5151 after v3.12.0), so it can be moved freely. Adds a regression test that expands NLOHMANN_JSON_SERIALIZE_ENUM_STRICT inside a namespace declaring its own templated_json_throw. Public API: no change (::templated_json_throw was an unreleased, unintentional global-namespace leak with no callers relying on its location). Overlaps #5698, which rewrites the same two macro call lines; the overlapping hunks are small and should be trivial to reconcile on rebase. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5708 item 2 * Factor the repeated JSON_HAS_RANGES/MinGW guard into one macro The std::ranges view conversion (excluded on MinGW because of its incomplete C++20 ranges support, #4916) was gated by the same #if JSON_HAS_RANGES && !defined(__MINGW32__) condition at seven independent sites in to_json.hpp and type_traits.hpp, with the MinGW rationale duplicated in two of them and missing from the rest. Since the sites come in matching pairs (one enables is_compatible_range_view and a view-based overload, the other adds the exclusion to the plain-array-type overload), a drift between any pair would produce an ambiguous or missing overload on exactly one platform. Add JSON_HAS_RANGE_VIEW_CONVERSION next to JSON_HAS_RANGES in macro_scope.hpp, combining both conditions with the #4916 reasoning in one place, #undef it in macro_unscope.hpp, and use it at all seven sites. This does not fold the MinGW check into JSON_HAS_RANGES itself: JSON_HAS_RANGES is user-overridable and also gates the enable_borrowed_range specialization in iteration_proxy.hpp, which is not excluded on MinGW. No behavior or public API change: JSON_HAS_RANGE_VIEW_CONVERSION expands to exactly the condition that was previously written out at each site. Overlaps #5585, #5600 and #3575, which touch the same to_json.hpp and type_traits.hpp lines; the change here is a mechanical search-and-replace of the guard condition and should rebase cleanly. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5708 item 11 * De-duplicate from_json.hpp's map and array-fallback bodies Several from_json() overload pairs in from_json.hpp were copies of each other, so a fix has to be applied twice (as #5681 already does): - from_json(..., std::map&) and from_json(..., std::unordered_map&) for non-string keys had identical 16-line bodies: array check, m.clear(), pair check loop, m.emplace(...). Route both through a new from_json_pair_array_to_map(j, m) helper. - The from_json_array_impl priority_tag<1> and priority_tag<0> fallbacks ran the same std::transform/std::inserter loop, differing only in ret.reserve(j.size()). Merge them into one body and, modeled on the existing from_json_object_reserve, add a from_json_array_reserve pair so the reserve() call is only made for ConstructibleArrayType that support it. Error ids (type_error.302), messages, diagnostic paths ((at(0)/at(1)) and behavior for types with/without reserve() are unchanged; only the duplication is removed. Public API: no change. Overlaps #5681, which changes the "&j" to "&p" line in both map bodies; the shared helper here should make that a one-line change instead of two on rebase. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5708 item 5 * Unify json_pointer's three array-index parsers array_index(), contains() and get_checked_or_null() each re-implemented the RFC 6901 array-index rules and the size_type range check: array_index() does the canonical parse and throws; contains() (which must not throw, #5395) re-validates every digit by hand and runs its own strtoull/ERANGE check before calling array_index() anyway, parsing every array token twice; get_checked_or_null() wraps array_index() in JSON_TRY/ JSON_INTERNAL_CATCH (detail::out_of_range&) to turn an unrepresentable index into "not found". Add a single private, noexcept parse_array_index(s, idx) returning an array_index_status (ok / leading_zero / not_a_number / unresolved / exceeds_size_type). array_index() becomes a thin wrapper mapping each status to the existing parse_error.106/109 or out_of_range.404/410; contains() and get_checked_or_null() switch on the status directly. This removes contains()'s digit-validation loop and its second strtoull call, and get_checked_or_null()'s JSON_TRY/JSON_INTERNAL_CATCH. Bugfix as a consequence: get_checked_or_null()'s JSON_TRY/ JSON_INTERNAL_CATCH was dead code under JSON_NOEXCEPTION (JSON_TRY expands to "if(true)" and the catch to "if(false)", so JSON_THROW's std::abort() ran unconditionally), meaning value() and contains() would abort instead of returning the default/false for an out-of-range-sized or oversized array index when exceptions are disabled (#5672). Switching on parse_array_index()'s return value instead of relying on an actual throw/catch fixes this: get_checked_or_null() now returns nullptr for array_index_status::unresolved/exceeds_size_type in every build configuration, and still calls JSON_THROW (aborting under JSON_NOEXCEPTION, as before) only for a malformed index (leading_zero/not_a_number), matching its documented @throw list. All existing error ids, messages and diagnostic paths are unchanged; a few reference tokens that used to fail contains()'s manual per-character validation (e.g. "1a") now fail via array_index_status::unresolved instead, with no observable difference since contains() only returns bool. Adds regression tests to unit-element_access2.cpp's "access on array type" section covering value() with an index that exceeds size_type and one with a trailing non-digit, both of which must yield the default value rather than abort/throw. Public API: no change. Overlaps #5700, #5614 and #5692, which touch the contains() and get_checked_or_null() array hunks; this change replaces those hunks with calls into the new shared parser, so a rebase will need to re-apply their token-handling changes (e.g. the empty-token case) on top of the switch statements here. Signed-off-by: Niels Lohmann <mail@nlohmann.me> #5708 item 4 * Regenerate single_include after merging develop The merge commit kept develop's single_include/nlohmann/json.hpp because make amalgamate saw it as up to date. Signed-off-by: Niels Lohmann <mail@nlohmann.me> * Address review: switch in array_index, drop redundant inline - json_pointer::array_index() dispatches on array_index_status with a switch, matching the other parse_array_index() caller - drop `inline` from the function templates this PR adds or moves in from_json.hpp - reword a comment that described the change rather than the code Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me>
601 lines
23 KiB
C++
601 lines
23 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/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>();
|
|
});
|
|
}
|
|
|
|
// element is not itself a C array: read it directly
|
|
template<typename BasicJsonType, typename T>
|
|
auto from_json_c_array_element(const BasicJsonType& j, T& e)
|
|
-> decltype(e = j.template get<T>(), void())
|
|
{
|
|
e = j.template get<T>();
|
|
}
|
|
|
|
// element is itself a C array: recurse one dimension at a time, so any rank is supported
|
|
template<typename BasicJsonType, typename T, std::size_t N>
|
|
void from_json_c_array_element(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays)
|
|
{
|
|
for (std::size_t i = 0; i < N; ++i)
|
|
{
|
|
from_json_c_array_element(j.at(i), arr[i]);
|
|
}
|
|
}
|
|
|
|
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<typename std::remove_all_extents<T>::type>(), void())
|
|
{
|
|
from_json_c_array_element(j, arr);
|
|
}
|
|
|
|
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>();
|
|
}
|
|
}
|
|
|
|
// reserve() is called through this pair (modeled on from_json_object_reserve)
|
|
// so from_json_array_impl below has a single body for both ConstructibleArrayType
|
|
// that support reserve() and those that don't.
|
|
template<typename ConstructibleArrayType>
|
|
auto from_json_array_reserve(ConstructibleArrayType& arr, typename ConstructibleArrayType::size_type size, priority_tag<1> /*unused*/)
|
|
-> decltype(arr.reserve(size), void())
|
|
{
|
|
arr.reserve(size);
|
|
}
|
|
|
|
template<typename ConstructibleArrayType>
|
|
void from_json_array_reserve(ConstructibleArrayType& /*arr*/, std::size_t /*size*/, priority_tag<0> /*unused*/)
|
|
{}
|
|
|
|
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(
|
|
j.template get<typename ConstructibleArrayType::value_type>(),
|
|
void())
|
|
{
|
|
using std::end;
|
|
|
|
ConstructibleArrayType ret;
|
|
from_json_array_reserve(ret, j.size(), priority_tag<1> {});
|
|
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.)
|
|
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(conjunction<disjunction<negation<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> {});
|
|
}
|
|
|
|
// shared body for std::map/std::unordered_map with a non-string Key: both
|
|
// containers are read from an array of [key, value] pairs the same way
|
|
template<typename BasicJsonType, typename MapType>
|
|
void from_json_pair_array_to_map(const BasicJsonType& j, MapType& 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<typename MapType::key_type>(), p.at(1).template get<typename MapType::mapped_type>());
|
|
}
|
|
}
|
|
|
|
template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator,
|
|
typename = enable_if_t < !std::is_constructible <
|
|
typename BasicJsonType::string_t, Key >::value >>
|
|
void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m)
|
|
{
|
|
from_json_pair_array_to_map(j, m);
|
|
}
|
|
|
|
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 >>
|
|
void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m)
|
|
{
|
|
from_json_pair_array_to_map(j, m);
|
|
}
|
|
|
|
#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM
|
|
|
|
// Workaround for MSVC 19.51 (and possibly later): 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
|