3 __| | __| | | | JSON for Modern C++
4 | | |__ | | | | | | version 2.1.1
5 |_____|_____|_____|_|___| https://github.com/nlohmann/json
7 Licensed under the MIT License <http://opensource.org/licenses/MIT>.
8 Copyright (c) 2013-2017 Niels Lohmann <http://nlohmann.me>.
10 Permission is hereby granted, free of charge, to any person obtaining a copy
11 of this software and associated documentation files (the "Software"), to deal
12 in the Software without restriction, including without limitation the rights
13 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 copies of the Software, and to permit persons to whom the Software is
15 furnished to do so, subject to the following conditions:
17 The above copyright notice and this permission notice shall be included in all
18 copies or substantial portions of the Software.
20 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 #ifndef NLOHMANN_JSON_HPP
30 #define NLOHMANN_JSON_HPP
32 #include <algorithm> // all_of, copy, fill, find, for_each, none_of, remove, reverse, transform
33 #include <array> // array
34 #include <cassert> // assert
35 #include <cctype> // isdigit
36 #include <ciso646> // and, not, or
37 #include <cmath> // isfinite, labs, ldexp, signbit
38 #include <cstddef> // nullptr_t, ptrdiff_t, size_t
39 #include <cstdint> // int64_t, uint64_t
40 #include <cstdlib> // abort, strtod, strtof, strtold, strtoul, strtoll, strtoull
41 #include <cstring> // strlen
42 #include <forward_list> // forward_list
43 #include <functional> // function, hash, less
44 #include <initializer_list> // initializer_list
45 #include <iomanip> // setw
46 #include <iostream> // istream, ostream
47 #include <iterator> // advance, begin, back_inserter, bidirectional_iterator_tag, distance, end, inserter, iterator, iterator_traits, next, random_access_iterator_tag, reverse_iterator
48 #include <limits> // numeric_limits
49 #include <locale> // locale
51 #include <memory> // addressof, allocator, allocator_traits, unique_ptr
52 #include <numeric> // accumulate
53 #include <sstream> // stringstream
54 #include <stdexcept> // domain_error, invalid_argument, out_of_range
55 #include <string> // getline, stoi, string, to_string
56 #include <type_traits> // add_pointer, conditional, decay, enable_if, false_type, integral_constant, is_arithmetic, is_base_of, is_const, is_constructible, is_convertible, is_default_constructible, is_enum, is_floating_point, is_integral, is_nothrow_move_assignable, is_nothrow_move_constructible, is_pointer, is_reference, is_same, is_scalar, is_signed, remove_const, remove_cv, remove_pointer, remove_reference, true_type, underlying_type
57 #include <utility> // declval, forward, make_pair, move, pair, swap
58 #include <vector> // vector
60 // allow for portable deprecation warnings
61 #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__)
62 #define JSON_DEPRECATED __attribute__((deprecated))
63 #elif defined(_MSC_VER)
64 #define JSON_DEPRECATED __declspec(deprecated)
66 #define JSON_DEPRECATED
69 // allow to disable exceptions
70 #if not defined(JSON_NOEXCEPTION) || defined(__EXCEPTIONS)
71 #define JSON_THROW(exception) throw exception
73 #define JSON_CATCH(exception) catch(exception)
75 #define JSON_THROW(exception) std::abort()
76 #define JSON_TRY if(true)
77 #define JSON_CATCH(exception) if(false)
81 @brief namespace for Niels Lohmann
82 @see https://github.com/nlohmann
89 @brief unnamed namespace with internal helper functions
91 This namespace collects some functions that could not be defined inside the
92 @ref basic_json class.
98 ///////////////////////////
99 // JSON type enumeration //
100 ///////////////////////////
103 @brief the JSON type enumeration
105 This enumeration collects the different JSON types. It is internally used to
106 distinguish the stored values, and the functions @ref basic_json::is_null(),
107 @ref basic_json::is_object(), @ref basic_json::is_array(),
108 @ref basic_json::is_string(), @ref basic_json::is_boolean(),
109 @ref basic_json::is_number() (with @ref basic_json::is_number_integer(),
110 @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()),
111 @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and
112 @ref basic_json::is_structured() rely on it.
114 @note There are three enumeration entries (number_integer, number_unsigned, and
115 number_float), because the library distinguishes these three types for numbers:
116 @ref basic_json::number_unsigned_t is used for unsigned integers,
117 @ref basic_json::number_integer_t is used for signed integers, and
118 @ref basic_json::number_float_t is used for floating-point numbers or to
119 approximate integers which do not fit in the limits of their respective type.
121 @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON
122 value with the default value for a given type
126 enum class value_t : uint8_t
128 null, ///< null value
129 object, ///< object (unordered set of name/value pairs)
130 array, ///< array (ordered collection of values)
131 string, ///< string value
132 boolean, ///< boolean value
133 number_integer, ///< number value (signed integer)
134 number_unsigned, ///< number value (unsigned integer)
135 number_float, ///< number value (floating-point)
136 discarded ///< discarded by the the parser callback function
140 @brief comparison operator for JSON types
142 Returns an ordering that is similar to Python:
143 - order: null < boolean < number < object < array < string
144 - furthermore, each type is not smaller than itself
148 inline bool operator<(const value_t lhs, const value_t rhs) noexcept
150 static constexpr std::array<uint8_t, 8> order = {{
162 // discarded values are not comparable
163 if (lhs == value_t::discarded or rhs == value_t::discarded)
168 return order[static_cast<std::size_t>(lhs)] <
169 order[static_cast<std::size_t>(rhs)];
177 // alias templates to reduce boilerplate
178 template<bool B, typename T = void>
179 using enable_if_t = typename std::enable_if<B, T>::type;
182 using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
184 // taken from http://stackoverflow.com/a/26936864/266378
186 using is_unscoped_enum =
187 std::integral_constant<bool, std::is_convertible<T, int>::value and
188 std::is_enum<T>::value>;
191 Implementation of two C++17 constructs: conjunction, negation. This is needed
192 to avoid evaluating all the traits in a condition
194 For example: not std::is_same<void, T>::value and has_value_type<T>::value
195 will not compile when T = void (on MSVC at least). Whereas
196 conjunction<negation<std::is_same<void, T>>, has_value_type<T>>::value will
197 stop evaluating if negation<...>::value == false
199 Please note that those constructs must be used with caution, since symbols can
200 become very long quickly (which can slow down compilation and cause MSVC
201 internal compiler errors). Only use it when you have to (see example ahead).
203 template<class...> struct conjunction : std::true_type {};
204 template<class B1> struct conjunction<B1> : B1 {};
205 template<class B1, class... Bn>
206 struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
208 template<class B> struct negation : std::integral_constant < bool, !B::value > {};
210 // dispatch utility (taken from ranges-v3)
211 template<unsigned N> struct priority_tag : priority_tag < N - 1 > {};
212 template<> struct priority_tag<0> {};
219 template<value_t> struct external_constructor;
222 struct external_constructor<value_t::boolean>
224 template<typename BasicJsonType>
225 static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept
227 j.m_type = value_t::boolean;
229 j.assert_invariant();
234 struct external_constructor<value_t::string>
236 template<typename BasicJsonType>
237 static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s)
239 j.m_type = value_t::string;
241 j.assert_invariant();
246 struct external_constructor<value_t::number_float>
248 template<typename BasicJsonType>
249 static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept
251 // replace infinity and NAN by null
252 if (not std::isfinite(val))
258 j.m_type = value_t::number_float;
261 j.assert_invariant();
266 struct external_constructor<value_t::number_unsigned>
268 template<typename BasicJsonType>
269 static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept
271 j.m_type = value_t::number_unsigned;
273 j.assert_invariant();
278 struct external_constructor<value_t::number_integer>
280 template<typename BasicJsonType>
281 static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept
283 j.m_type = value_t::number_integer;
285 j.assert_invariant();
290 struct external_constructor<value_t::array>
292 template<typename BasicJsonType>
293 static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr)
295 j.m_type = value_t::array;
297 j.assert_invariant();
300 template<typename BasicJsonType, typename CompatibleArrayType,
301 enable_if_t<not std::is_same<CompatibleArrayType,
302 typename BasicJsonType::array_t>::value,
304 static void construct(BasicJsonType& j, const CompatibleArrayType& arr)
308 j.m_type = value_t::array;
309 j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr));
310 j.assert_invariant();
315 struct external_constructor<value_t::object>
317 template<typename BasicJsonType>
318 static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj)
320 j.m_type = value_t::object;
322 j.assert_invariant();
325 template<typename BasicJsonType, typename CompatibleObjectType,
326 enable_if_t<not std::is_same<CompatibleObjectType,
327 typename BasicJsonType::object_t>::value,
329 static void construct(BasicJsonType& j, const CompatibleObjectType& obj)
334 j.m_type = value_t::object;
335 j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj));
336 j.assert_invariant();
341 ////////////////////////
342 // has_/is_ functions //
343 ////////////////////////
346 @brief Helper to determine whether there's a key_type for T.
348 This helper is used to tell associative containers apart from other containers
349 such as sequence containers. For instance, `std::map` passes the test as it
350 contains a `mapped_type`, whereas `std::vector` fails the test.
352 @sa http://stackoverflow.com/a/7728728/266378
353 @since version 1.0.0, overworked in version 2.0.6
355 #define NLOHMANN_JSON_HAS_HELPER(type) \
356 template<typename T> struct has_##type { \
358 template<typename U, typename = typename U::type> \
359 static int detect(U &&); \
360 static void detect(...); \
362 static constexpr bool value = \
363 std::is_integral<decltype(detect(std::declval<T>()))>::value; \
366 NLOHMANN_JSON_HAS_HELPER(mapped_type);
367 NLOHMANN_JSON_HAS_HELPER(key_type);
368 NLOHMANN_JSON_HAS_HELPER(value_type);
369 NLOHMANN_JSON_HAS_HELPER(iterator);
371 #undef NLOHMANN_JSON_HAS_HELPER
374 template<bool B, class RealType, class CompatibleObjectType>
375 struct is_compatible_object_type_impl : std::false_type {};
377 template<class RealType, class CompatibleObjectType>
378 struct is_compatible_object_type_impl<true, RealType, CompatibleObjectType>
380 static constexpr auto value =
381 std::is_constructible<typename RealType::key_type,
382 typename CompatibleObjectType::key_type>::value and
383 std::is_constructible<typename RealType::mapped_type,
384 typename CompatibleObjectType::mapped_type>::value;
387 template<class BasicJsonType, class CompatibleObjectType>
388 struct is_compatible_object_type
390 static auto constexpr value = is_compatible_object_type_impl <
391 conjunction<negation<std::is_same<void, CompatibleObjectType>>,
392 has_mapped_type<CompatibleObjectType>,
393 has_key_type<CompatibleObjectType>>::value,
394 typename BasicJsonType::object_t, CompatibleObjectType >::value;
397 template<typename BasicJsonType, typename T>
398 struct is_basic_json_nested_type
400 static auto constexpr value = std::is_same<T, typename BasicJsonType::iterator>::value or
401 std::is_same<T, typename BasicJsonType::const_iterator>::value or
402 std::is_same<T, typename BasicJsonType::reverse_iterator>::value or
403 std::is_same<T, typename BasicJsonType::const_reverse_iterator>::value or
404 std::is_same<T, typename BasicJsonType::json_pointer>::value;
407 template<class BasicJsonType, class CompatibleArrayType>
408 struct is_compatible_array_type
410 static auto constexpr value =
411 conjunction<negation<std::is_same<void, CompatibleArrayType>>,
412 negation<is_compatible_object_type<
413 BasicJsonType, CompatibleArrayType>>,
414 negation<std::is_constructible<typename BasicJsonType::string_t,
415 CompatibleArrayType>>,
416 negation<is_basic_json_nested_type<BasicJsonType, CompatibleArrayType>>,
417 has_value_type<CompatibleArrayType>,
418 has_iterator<CompatibleArrayType>>::value;
421 template<bool, typename, typename>
422 struct is_compatible_integer_type_impl : std::false_type {};
424 template<typename RealIntegerType, typename CompatibleNumberIntegerType>
425 struct is_compatible_integer_type_impl<true, RealIntegerType, CompatibleNumberIntegerType>
427 // is there an assert somewhere on overflows?
428 using RealLimits = std::numeric_limits<RealIntegerType>;
429 using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>;
431 static constexpr auto value =
432 std::is_constructible<RealIntegerType,
433 CompatibleNumberIntegerType>::value and
434 CompatibleLimits::is_integer and
435 RealLimits::is_signed == CompatibleLimits::is_signed;
438 template<typename RealIntegerType, typename CompatibleNumberIntegerType>
439 struct is_compatible_integer_type
441 static constexpr auto value =
442 is_compatible_integer_type_impl <
443 std::is_integral<CompatibleNumberIntegerType>::value and
444 not std::is_same<bool, CompatibleNumberIntegerType>::value,
445 RealIntegerType, CompatibleNumberIntegerType > ::value;
449 // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists
450 template<typename BasicJsonType, typename T>
454 // also check the return type of from_json
455 template<typename U, typename = enable_if_t<std::is_same<void, decltype(uncvref_t<U>::from_json(
456 std::declval<BasicJsonType>(), std::declval<T&>()))>::value>>
457 static int detect(U&&);
458 static void detect(...);
461 static constexpr bool value = std::is_integral<decltype(
462 detect(std::declval<typename BasicJsonType::template json_serializer<T, void > >()))>::value;
465 // This trait checks if JSONSerializer<T>::from_json(json const&) exists
466 // this overload is used for non-default-constructible user-defined-types
467 template<typename BasicJsonType, typename T>
468 struct has_non_default_from_json
473 typename = enable_if_t<std::is_same<
474 T, decltype(uncvref_t<U>::from_json(std::declval<BasicJsonType>()))>::value >>
475 static int detect(U&&);
476 static void detect(...);
479 static constexpr bool value = std::is_integral<decltype(detect(
480 std::declval<typename BasicJsonType::template json_serializer<T, void> >()))>::value;
483 // This trait checks if BasicJsonType::json_serializer<T>::to_json exists
484 template<typename BasicJsonType, typename T>
488 template<typename U, typename = decltype(uncvref_t<U>::to_json(
489 std::declval<BasicJsonType&>(), std::declval<T>()))>
490 static int detect(U&&);
491 static void detect(...);
494 static constexpr bool value = std::is_integral<decltype(detect(
495 std::declval<typename BasicJsonType::template json_serializer<T, void> >()))>::value;
503 template<typename BasicJsonType, typename T, enable_if_t<
504 std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0>
505 void to_json(BasicJsonType& j, T b) noexcept
507 external_constructor<value_t::boolean>::construct(j, b);
510 template<typename BasicJsonType, typename CompatibleString,
511 enable_if_t<std::is_constructible<typename BasicJsonType::string_t,
512 CompatibleString>::value, int> = 0>
513 void to_json(BasicJsonType& j, const CompatibleString& s)
515 external_constructor<value_t::string>::construct(j, s);
518 template<typename BasicJsonType, typename FloatType,
519 enable_if_t<std::is_floating_point<FloatType>::value, int> = 0>
520 void to_json(BasicJsonType& j, FloatType val) noexcept
522 external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val));
526 typename BasicJsonType, typename CompatibleNumberUnsignedType,
527 enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t,
528 CompatibleNumberUnsignedType>::value, int> = 0 >
529 void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept
531 external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val));
535 typename BasicJsonType, typename CompatibleNumberIntegerType,
536 enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t,
537 CompatibleNumberIntegerType>::value, int> = 0 >
538 void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept
540 external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val));
543 template<typename BasicJsonType, typename UnscopedEnumType,
544 enable_if_t<is_unscoped_enum<UnscopedEnumType>::value, int> = 0>
545 void to_json(BasicJsonType& j, UnscopedEnumType e) noexcept
547 external_constructor<value_t::number_integer>::construct(j, e);
551 typename BasicJsonType, typename CompatibleArrayType,
553 is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value or
554 std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value,
556 void to_json(BasicJsonType& j, const CompatibleArrayType& arr)
558 external_constructor<value_t::array>::construct(j, arr);
562 typename BasicJsonType, typename CompatibleObjectType,
563 enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value,
565 void to_json(BasicJsonType& j, const CompatibleObjectType& arr)
567 external_constructor<value_t::object>::construct(j, arr);
575 // overloads for basic_json template parameters
576 template<typename BasicJsonType, typename ArithmeticType,
577 enable_if_t<std::is_arithmetic<ArithmeticType>::value and
578 not std::is_same<ArithmeticType,
579 typename BasicJsonType::boolean_t>::value,
581 void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val)
583 switch (static_cast<value_t>(j))
585 case value_t::number_unsigned:
587 val = static_cast<ArithmeticType>(
588 *j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
591 case value_t::number_integer:
593 val = static_cast<ArithmeticType>(
594 *j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
597 case value_t::number_float:
599 val = static_cast<ArithmeticType>(
600 *j.template get_ptr<const typename BasicJsonType::number_float_t*>());
606 std::domain_error("type must be number, but is " + j.type_name()));
611 template<typename BasicJsonType>
612 void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b)
614 if (not j.is_boolean())
616 JSON_THROW(std::domain_error("type must be boolean, but is " + j.type_name()));
618 b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>();
621 template<typename BasicJsonType>
622 void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s)
624 if (not j.is_string())
626 JSON_THROW(std::domain_error("type must be string, but is " + j.type_name()));
628 s = *j.template get_ptr<const typename BasicJsonType::string_t*>();
631 template<typename BasicJsonType>
632 void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val)
634 get_arithmetic_value(j, val);
637 template<typename BasicJsonType>
638 void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val)
640 get_arithmetic_value(j, val);
643 template<typename BasicJsonType>
644 void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val)
646 get_arithmetic_value(j, val);
649 template<typename BasicJsonType, typename UnscopedEnumType,
650 enable_if_t<is_unscoped_enum<UnscopedEnumType>::value, int> = 0>
651 void from_json(const BasicJsonType& j, UnscopedEnumType& e)
653 typename std::underlying_type<UnscopedEnumType>::type val;
654 get_arithmetic_value(j, val);
655 e = static_cast<UnscopedEnumType>(val);
658 template<typename BasicJsonType>
659 void from_json(const BasicJsonType& j, typename BasicJsonType::array_t& arr)
661 if (not j.is_array())
663 JSON_THROW(std::domain_error("type must be array, but is " + j.type_name()));
665 arr = *j.template get_ptr<const typename BasicJsonType::array_t*>();
668 // forward_list doesn't have an insert method
669 template<typename BasicJsonType, typename T, typename Allocator>
670 void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l)
672 // do not perform the check when user wants to retrieve jsons
673 // (except when it's null.. ?)
676 JSON_THROW(std::domain_error("type must be array, but is " + j.type_name()));
678 if (not std::is_same<T, BasicJsonType>::value)
680 if (not j.is_array())
682 JSON_THROW(std::domain_error("type must be array, but is " + j.type_name()));
685 for (auto it = j.rbegin(), end = j.rend(); it != end; ++it)
687 l.push_front(it->template get<T>());
691 template<typename BasicJsonType, typename CompatibleArrayType>
692 void from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<0>)
697 std::transform(j.begin(), j.end(),
698 std::inserter(arr, end(arr)), [](const BasicJsonType & i)
700 // get<BasicJsonType>() returns *this, this won't call a from_json
701 // method when value_type is BasicJsonType
702 return i.template get<typename CompatibleArrayType::value_type>();
706 template<typename BasicJsonType, typename CompatibleArrayType>
707 auto from_json_array_impl(const BasicJsonType& j, CompatibleArrayType& arr, priority_tag<1>)
709 arr.reserve(std::declval<typename CompatibleArrayType::size_type>()),
715 arr.reserve(j.size());
717 j.begin(), j.end(), std::inserter(arr, end(arr)), [](const BasicJsonType & i)
719 // get<BasicJsonType>() returns *this, this won't call a from_json
720 // method when value_type is BasicJsonType
721 return i.template get<typename CompatibleArrayType::value_type>();
725 template<typename BasicJsonType, typename CompatibleArrayType,
726 enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and
727 not std::is_same<typename BasicJsonType::array_t, CompatibleArrayType>::value, int> = 0>
728 void from_json(const BasicJsonType& j, CompatibleArrayType& arr)
732 JSON_THROW(std::domain_error("type must be array, but is " + j.type_name()));
735 // when T == BasicJsonType, do not check if value_t is correct
736 if (not std::is_same<typename CompatibleArrayType::value_type, BasicJsonType>::value)
738 if (not j.is_array())
740 JSON_THROW(std::domain_error("type must be array, but is " + j.type_name()));
743 from_json_array_impl(j, arr, priority_tag<1> {});
746 template<typename BasicJsonType, typename CompatibleObjectType,
747 enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value, int> = 0>
748 void from_json(const BasicJsonType& j, CompatibleObjectType& obj)
750 if (not j.is_object())
752 JSON_THROW(std::domain_error("type must be object, but is " + j.type_name()));
755 auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>();
758 // we could avoid the assignment, but this might require a for loop, which
759 // might be less efficient than the container constructor for some
760 // containers (would it?)
761 obj = CompatibleObjectType(begin(*inner_object), end(*inner_object));
764 // overload for arithmetic types, not chosen for basic_json template arguments
765 // (BooleanType, etc..); note: Is it really necessary to provide explicit
766 // overloads for boolean_t etc. in case of a custom BooleanType which is not
767 // an arithmetic type?
768 template<typename BasicJsonType, typename ArithmeticType,
770 std::is_arithmetic<ArithmeticType>::value and
771 not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and
772 not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and
773 not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and
774 not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value,
776 void from_json(const BasicJsonType& j, ArithmeticType& val)
778 switch (static_cast<value_t>(j))
780 case value_t::number_unsigned:
782 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>());
785 case value_t::number_integer:
787 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>());
790 case value_t::number_float:
792 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>());
795 case value_t::boolean:
797 val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>());
802 JSON_THROW(std::domain_error("type must be number, but is " + j.type_name()));
810 template<typename BasicJsonType, typename T>
811 auto call(BasicJsonType& j, T&& val, priority_tag<1>) const noexcept(noexcept(to_json(j, std::forward<T>(val))))
812 -> decltype(to_json(j, std::forward<T>(val)), void())
814 return to_json(j, std::forward<T>(val));
817 template<typename BasicJsonType, typename T>
818 void call(BasicJsonType&, T&&, priority_tag<0>) const noexcept
820 static_assert(sizeof(BasicJsonType) == 0,
821 "could not find to_json() method in T's namespace");
825 template<typename BasicJsonType, typename T>
826 void operator()(BasicJsonType& j, T&& val) const
827 noexcept(noexcept(std::declval<to_json_fn>().call(j, std::forward<T>(val), priority_tag<1> {})))
829 return call(j, std::forward<T>(val), priority_tag<1> {});
836 template<typename BasicJsonType, typename T>
837 auto call(const BasicJsonType& j, T& val, priority_tag<1>) const
838 noexcept(noexcept(from_json(j, val)))
839 -> decltype(from_json(j, val), void())
841 return from_json(j, val);
844 template<typename BasicJsonType, typename T>
845 void call(const BasicJsonType&, T&, priority_tag<0>) const noexcept
847 static_assert(sizeof(BasicJsonType) == 0,
848 "could not find from_json() method in T's namespace");
852 template<typename BasicJsonType, typename T>
853 void operator()(const BasicJsonType& j, T& val) const
854 noexcept(noexcept(std::declval<from_json_fn>().call(j, val, priority_tag<1> {})))
856 return call(j, val, priority_tag<1> {});
860 // taken from ranges-v3
864 static constexpr T value{};
868 constexpr T static_const<T>::value;
869 } // namespace detail
872 /// namespace to hold default `to_json` / `from_json` functions
875 constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value;
876 constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value;
881 @brief default JSONSerializer template argument
883 This serializer ignores the template arguments and uses ADL
884 ([argument-dependent lookup](http://en.cppreference.com/w/cpp/language/adl))
887 template<typename = void, typename = void>
888 struct adl_serializer
891 @brief convert a JSON value to any value type
893 This function is usually called by the `get()` function of the
894 @ref basic_json class (either explicit or via conversion operators).
896 @param[in] j JSON value to read from
897 @param[in,out] val value to write to
899 template<typename BasicJsonType, typename ValueType>
900 static void from_json(BasicJsonType&& j, ValueType& val) noexcept(
901 noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val)))
903 ::nlohmann::from_json(std::forward<BasicJsonType>(j), val);
907 @brief convert any value type to a JSON value
909 This function is usually called by the constructors of the @ref basic_json
912 @param[in,out] j JSON value to write to
913 @param[in] val value to read from
915 template<typename BasicJsonType, typename ValueType>
916 static void to_json(BasicJsonType& j, ValueType&& val) noexcept(
917 noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val))))
919 ::nlohmann::to_json(j, std::forward<ValueType>(val));
925 @brief a class to store JSON values
927 @tparam ObjectType type for JSON objects (`std::map` by default; will be used
929 @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
931 @tparam StringType type for JSON strings and object keys (`std::string` by
932 default; will be used in @ref string_t)
933 @tparam BooleanType type for JSON booleans (`bool` by default; will be used
935 @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
936 default; will be used in @ref number_integer_t)
937 @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
938 `uint64_t` by default; will be used in @ref number_unsigned_t)
939 @tparam NumberFloatType type for JSON floating-point numbers (`double` by
940 default; will be used in @ref number_float_t)
941 @tparam AllocatorType type of the allocator to use (`std::allocator` by
943 @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
944 and `from_json()` (@ref adl_serializer by default)
946 @requirement The class satisfies the following concept requirements:
948 - [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):
949 JSON values can be default constructed. The result will be a JSON null
951 - [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):
952 A JSON value can be constructed from an rvalue argument.
953 - [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):
954 A JSON value can be copy-constructed from an lvalue expression.
955 - [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):
956 A JSON value van be assigned from an rvalue argument.
957 - [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):
958 A JSON value can be copy-assigned from an lvalue expression.
959 - [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):
960 JSON values can be destructed.
962 - [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):
964 [standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
965 All non-static data members are private and standard layout types, the
966 class has no virtual functions or (virtual) base classes.
968 - [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):
969 JSON values can be compared with `==`, see @ref
970 operator==(const_reference,const_reference).
971 - [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):
972 JSON values can be compared with `<`, see @ref
973 operator<(const_reference,const_reference).
974 - [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):
975 Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
976 other compatible types, using unqualified function call @ref swap().
977 - [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):
978 JSON values can be compared against `std::nullptr_t` objects which are used
979 to model the `null` value.
981 - [Container](http://en.cppreference.com/w/cpp/concept/Container):
982 JSON values can be used like STL containers and provide iterator access.
983 - [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);
984 JSON values can be used like STL containers and provide reverse iterator
987 @invariant The member variables @a m_value and @a m_type have the following
989 - If `m_type == value_t::object`, then `m_value.object != nullptr`.
990 - If `m_type == value_t::array`, then `m_value.array != nullptr`.
991 - If `m_type == value_t::string`, then `m_value.string != nullptr`.
992 The invariants are checked by member function assert_invariant().
995 @note ObjectType trick from http://stackoverflow.com/a/9860911
998 @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
999 Format](http://rfc7159.net/rfc7159)
1001 @since version 1.0.0
1006 template<typename U, typename V, typename... Args> class ObjectType = std::map,
1007 template<typename U, typename... Args> class ArrayType = std::vector,
1008 class StringType = std::string,
1009 class BooleanType = bool,
1010 class NumberIntegerType = std::int64_t,
1011 class NumberUnsignedType = std::uint64_t,
1012 class NumberFloatType = double,
1013 template<typename U> class AllocatorType = std::allocator,
1014 template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer
1019 template<detail::value_t> friend struct detail::external_constructor;
1020 /// workaround type for MSVC
1021 using basic_json_t = basic_json<ObjectType, ArrayType, StringType,
1022 BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType,
1023 AllocatorType, JSONSerializer>;
1026 using value_t = detail::value_t;
1027 // forward declarations
1028 template<typename U> class iter_impl;
1029 template<typename Base> class json_reverse_iterator;
1031 template<typename T, typename SFINAE>
1032 using json_serializer = JSONSerializer<T, SFINAE>;
1034 /////////////////////
1035 // container types //
1036 /////////////////////
1038 /// @name container types
1039 /// The canonic container types to use @ref basic_json like any other STL
1043 /// the type of elements in a basic_json container
1044 using value_type = basic_json;
1046 /// the type of an element reference
1047 using reference = value_type&;
1048 /// the type of an element const reference
1049 using const_reference = const value_type&;
1051 /// a type to represent differences between iterators
1052 using difference_type = std::ptrdiff_t;
1053 /// a type to represent container sizes
1054 using size_type = std::size_t;
1056 /// the allocator type
1057 using allocator_type = AllocatorType<basic_json>;
1059 /// the type of an element pointer
1060 using pointer = typename std::allocator_traits<allocator_type>::pointer;
1061 /// the type of an element const pointer
1062 using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
1064 /// an iterator for a basic_json container
1065 using iterator = iter_impl<basic_json>;
1066 /// a const iterator for a basic_json container
1067 using const_iterator = iter_impl<const basic_json>;
1068 /// a reverse iterator for a basic_json container
1069 using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
1070 /// a const reverse iterator for a basic_json container
1071 using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
1077 @brief returns the allocator associated with the container
1079 static allocator_type get_allocator()
1081 return allocator_type();
1085 @brief returns version information on the library
1087 This function returns a JSON object with information about the library,
1088 including the version number and information on the platform and compiler.
1090 @return JSON object holding version information
1092 ----------- | ---------------
1093 `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version).
1094 `copyright` | The copyright line for the library as string.
1095 `name` | The name of the library as string.
1096 `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
1097 `url` | The URL of the project as string.
1098 `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string).
1100 @liveexample{The following code shows an example output of the `meta()`
1103 @complexity Constant.
1107 static basic_json meta()
1111 result["copyright"] = "(C) 2013-2017 Niels Lohmann";
1112 result["name"] = "JSON for Modern C++";
1113 result["url"] = "https://github.com/nlohmann/json";
1116 {"string", "2.1.1"},
1123 result["platform"] = "win32";
1124 #elif defined __linux__
1125 result["platform"] = "linux";
1126 #elif defined __APPLE__
1127 result["platform"] = "apple";
1128 #elif defined __unix__
1129 result["platform"] = "unix";
1131 result["platform"] = "unknown";
1134 #if defined(__clang__)
1135 result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
1136 #elif defined(__ICC) || defined(__INTEL_COMPILER)
1137 result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
1138 #elif defined(__GNUC__) || defined(__GNUG__)
1139 result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
1140 #elif defined(__HP_cc) || defined(__HP_aCC)
1141 result["compiler"] = "hp"
1142 #elif defined(__IBMCPP__)
1143 result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
1144 #elif defined(_MSC_VER)
1145 result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
1146 #elif defined(__PGI)
1147 result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
1148 #elif defined(__SUNPRO_CC)
1149 result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
1151 result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
1155 result["compiler"]["c++"] = std::to_string(__cplusplus);
1157 result["compiler"]["c++"] = "unknown";
1163 ///////////////////////////
1164 // JSON value data types //
1165 ///////////////////////////
1167 /// @name JSON value data types
1168 /// The data types to store a JSON value. These types are derived from
1169 /// the template arguments passed to class @ref basic_json.
1173 @brief a type for an object
1175 [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
1176 > An object is an unordered collection of zero or more name/value pairs,
1177 > where a name is a string and a value is a string, number, boolean, null,
1180 To store objects in C++, a type is defined by the template parameters
1183 @tparam ObjectType the container to store objects (e.g., `std::map` or
1184 `std::unordered_map`)
1185 @tparam StringType the type of the keys or names (e.g., `std::string`).
1186 The comparison function `std::less<StringType>` is used to order elements
1187 inside the container.
1188 @tparam AllocatorType the allocator to use for objects (e.g.,
1193 With the default values for @a ObjectType (`std::map`), @a StringType
1194 (`std::string`), and @a AllocatorType (`std::allocator`), the default
1195 value for @a object_t is:
1199 std::string, // key_type
1200 basic_json, // value_type
1201 std::less<std::string>, // key_compare
1202 std::allocator<std::pair<const std::string, basic_json>> // allocator_type
1208 The choice of @a object_t influences the behavior of the JSON class. With
1209 the default type, objects have the following behavior:
1211 - When all names are unique, objects will be interoperable in the sense
1212 that all software implementations receiving that object will agree on
1213 the name-value mappings.
1214 - When the names within an object are not unique, later stored name/value
1215 pairs overwrite previously stored name/value pairs, leaving the used
1216 names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will
1217 be treated as equal and both stored as `{"key": 1}`.
1218 - Internally, name/value pairs are stored in lexicographical order of the
1219 names. Objects will also be serialized (see @ref dump) in this order.
1220 For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
1221 and serialized as `{"a": 2, "b": 1}`.
1222 - When comparing objects, the order of the name/value pairs is irrelevant.
1223 This makes objects interoperable in the sense that they will not be
1224 affected by these differences. For instance, `{"b": 1, "a": 2}` and
1225 `{"a": 2, "b": 1}` will be treated as equal.
1229 [RFC 7159](http://rfc7159.net/rfc7159) specifies:
1230 > An implementation may set limits on the maximum depth of nesting.
1232 In this class, the object's limit of nesting is not constraint explicitly.
1233 However, a maximum depth of nesting may be introduced by the compiler or
1234 runtime environment. A theoretical limit can be queried by calling the
1235 @ref max_size function of a JSON object.
1239 Objects are stored as pointers in a @ref basic_json type. That is, for any
1240 access to object values, a pointer of type `object_t*` must be
1243 @sa @ref array_t -- type for an array value
1245 @since version 1.0.0
1247 @note The order name/value pairs are added to the object is *not*
1248 preserved by the library. Therefore, iterating an object may return
1249 name/value pairs in a different order than they were originally stored. In
1250 fact, keys will be traversed in alphabetical order as `std::map` with
1251 `std::less` is used by default. Please note this behavior conforms to [RFC
1252 7159](http://rfc7159.net/rfc7159), because any order implements the
1253 specified "unordered" nature of JSON objects.
1255 using object_t = ObjectType<StringType,
1257 std::less<StringType>,
1258 AllocatorType<std::pair<const StringType,
1262 @brief a type for an array
1264 [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
1265 > An array is an ordered sequence of zero or more values.
1267 To store objects in C++, a type is defined by the template parameters
1270 @tparam ArrayType container type to store arrays (e.g., `std::vector` or
1272 @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
1276 With the default values for @a ArrayType (`std::vector`) and @a
1277 AllocatorType (`std::allocator`), the default value for @a array_t is:
1281 basic_json, // value_type
1282 std::allocator<basic_json> // allocator_type
1288 [RFC 7159](http://rfc7159.net/rfc7159) specifies:
1289 > An implementation may set limits on the maximum depth of nesting.
1291 In this class, the array's limit of nesting is not constraint explicitly.
1292 However, a maximum depth of nesting may be introduced by the compiler or
1293 runtime environment. A theoretical limit can be queried by calling the
1294 @ref max_size function of a JSON array.
1298 Arrays are stored as pointers in a @ref basic_json type. That is, for any
1299 access to array values, a pointer of type `array_t*` must be dereferenced.
1301 @sa @ref object_t -- type for an object value
1303 @since version 1.0.0
1305 using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
1308 @brief a type for a string
1310 [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
1311 > A string is a sequence of zero or more Unicode characters.
1313 To store objects in C++, a type is defined by the template parameter
1314 described below. Unicode values are split by the JSON class into
1315 byte-sized characters during deserialization.
1317 @tparam StringType the container to store strings (e.g., `std::string`).
1318 Note this container is used for keys/names in objects, see @ref object_t.
1322 With the default values for @a StringType (`std::string`), the default
1323 value for @a string_t is:
1331 Strings are stored in UTF-8 encoding. Therefore, functions like
1332 `std::string::size()` or `std::string::length()` return the number of
1333 bytes in the string rather than the number of characters or glyphs.
1335 #### String comparison
1337 [RFC 7159](http://rfc7159.net/rfc7159) states:
1338 > Software implementations are typically required to test names of object
1339 > members for equality. Implementations that transform the textual
1340 > representation into sequences of Unicode code units and then perform the
1341 > comparison numerically, code unit by code unit, are interoperable in the
1342 > sense that implementations will agree in all cases on equality or
1343 > inequality of two strings. For example, implementations that compare
1344 > strings with escaped characters unconverted may incorrectly find that
1345 > `"a\\b"` and `"a\u005Cb"` are not equal.
1347 This implementation is interoperable as it does compare strings code unit
1352 String values are stored as pointers in a @ref basic_json type. That is,
1353 for any access to string values, a pointer of type `string_t*` must be
1356 @since version 1.0.0
1358 using string_t = StringType;
1361 @brief a type for a boolean
1363 [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
1364 type which differentiates the two literals `true` and `false`.
1366 To store objects in C++, a type is defined by the template parameter @a
1367 BooleanType which chooses the type to use.
1371 With the default values for @a BooleanType (`bool`), the default value for
1380 Boolean values are stored directly inside a @ref basic_json type.
1382 @since version 1.0.0
1384 using boolean_t = BooleanType;
1387 @brief a type for a number (integer)
1389 [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
1390 > The representation of numbers is similar to that used in most
1391 > programming languages. A number is represented in base 10 using decimal
1392 > digits. It contains an integer component that may be prefixed with an
1393 > optional minus sign, which may be followed by a fraction part and/or an
1394 > exponent part. Leading zeros are not allowed. (...) Numeric values that
1395 > cannot be represented in the grammar below (such as Infinity and NaN)
1396 > are not permitted.
1398 This description includes both integer and floating-point numbers.
1399 However, C++ allows more precise storage if it is known whether the number
1400 is a signed integer, an unsigned integer or a floating-point number.
1401 Therefore, three different types, @ref number_integer_t, @ref
1402 number_unsigned_t and @ref number_float_t are used.
1404 To store integer numbers in C++, a type is defined by the template
1405 parameter @a NumberIntegerType which chooses the type to use.
1409 With the default values for @a NumberIntegerType (`int64_t`), the default
1410 value for @a number_integer_t is:
1416 #### Default behavior
1418 - The restrictions about leading zeros is not enforced in C++. Instead,
1419 leading zeros in integer literals lead to an interpretation as octal
1420 number. Internally, the value will be stored as decimal number. For
1421 instance, the C++ integer literal `010` will be serialized to `8`.
1422 During deserialization, leading zeros yield an error.
1423 - Not-a-number (NaN) values will be serialized to `null`.
1427 [RFC 7159](http://rfc7159.net/rfc7159) specifies:
1428 > An implementation may set limits on the range and precision of numbers.
1430 When the default type is used, the maximal integer number that can be
1431 stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
1432 that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
1433 that are out of range will yield over/underflow when used in a
1434 constructor. During deserialization, too large or small integer numbers
1435 will be automatically be stored as @ref number_unsigned_t or @ref
1438 [RFC 7159](http://rfc7159.net/rfc7159) further states:
1439 > Note that when such software is used, numbers that are integers and are
1440 > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
1441 > that implementations will agree exactly on their numeric values.
1443 As this range is a subrange of the exactly supported range [INT64_MIN,
1444 INT64_MAX], this class's integer type is interoperable.
1448 Integer number values are stored directly inside a @ref basic_json type.
1450 @sa @ref number_float_t -- type for number values (floating-point)
1452 @sa @ref number_unsigned_t -- type for number values (unsigned integer)
1454 @since version 1.0.0
1456 using number_integer_t = NumberIntegerType;
1459 @brief a type for a number (unsigned)
1461 [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
1462 > The representation of numbers is similar to that used in most
1463 > programming languages. A number is represented in base 10 using decimal
1464 > digits. It contains an integer component that may be prefixed with an
1465 > optional minus sign, which may be followed by a fraction part and/or an
1466 > exponent part. Leading zeros are not allowed. (...) Numeric values that
1467 > cannot be represented in the grammar below (such as Infinity and NaN)
1468 > are not permitted.
1470 This description includes both integer and floating-point numbers.
1471 However, C++ allows more precise storage if it is known whether the number
1472 is a signed integer, an unsigned integer or a floating-point number.
1473 Therefore, three different types, @ref number_integer_t, @ref
1474 number_unsigned_t and @ref number_float_t are used.
1476 To store unsigned integer numbers in C++, a type is defined by the
1477 template parameter @a NumberUnsignedType which chooses the type to use.
1481 With the default values for @a NumberUnsignedType (`uint64_t`), the
1482 default value for @a number_unsigned_t is:
1488 #### Default behavior
1490 - The restrictions about leading zeros is not enforced in C++. Instead,
1491 leading zeros in integer literals lead to an interpretation as octal
1492 number. Internally, the value will be stored as decimal number. For
1493 instance, the C++ integer literal `010` will be serialized to `8`.
1494 During deserialization, leading zeros yield an error.
1495 - Not-a-number (NaN) values will be serialized to `null`.
1499 [RFC 7159](http://rfc7159.net/rfc7159) specifies:
1500 > An implementation may set limits on the range and precision of numbers.
1502 When the default type is used, the maximal integer number that can be
1503 stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
1504 number that can be stored is `0`. Integer numbers that are out of range
1505 will yield over/underflow when used in a constructor. During
1506 deserialization, too large or small integer numbers will be automatically
1507 be stored as @ref number_integer_t or @ref number_float_t.
1509 [RFC 7159](http://rfc7159.net/rfc7159) further states:
1510 > Note that when such software is used, numbers that are integers and are
1511 > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
1512 > that implementations will agree exactly on their numeric values.
1514 As this range is a subrange (when considered in conjunction with the
1515 number_integer_t type) of the exactly supported range [0, UINT64_MAX],
1516 this class's integer type is interoperable.
1520 Integer number values are stored directly inside a @ref basic_json type.
1522 @sa @ref number_float_t -- type for number values (floating-point)
1523 @sa @ref number_integer_t -- type for number values (integer)
1525 @since version 2.0.0
1527 using number_unsigned_t = NumberUnsignedType;
1530 @brief a type for a number (floating-point)
1532 [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
1533 > The representation of numbers is similar to that used in most
1534 > programming languages. A number is represented in base 10 using decimal
1535 > digits. It contains an integer component that may be prefixed with an
1536 > optional minus sign, which may be followed by a fraction part and/or an
1537 > exponent part. Leading zeros are not allowed. (...) Numeric values that
1538 > cannot be represented in the grammar below (such as Infinity and NaN)
1539 > are not permitted.
1541 This description includes both integer and floating-point numbers.
1542 However, C++ allows more precise storage if it is known whether the number
1543 is a signed integer, an unsigned integer or a floating-point number.
1544 Therefore, three different types, @ref number_integer_t, @ref
1545 number_unsigned_t and @ref number_float_t are used.
1547 To store floating-point numbers in C++, a type is defined by the template
1548 parameter @a NumberFloatType which chooses the type to use.
1552 With the default values for @a NumberFloatType (`double`), the default
1553 value for @a number_float_t is:
1559 #### Default behavior
1561 - The restrictions about leading zeros is not enforced in C++. Instead,
1562 leading zeros in floating-point literals will be ignored. Internally,
1563 the value will be stored as decimal number. For instance, the C++
1564 floating-point literal `01.2` will be serialized to `1.2`. During
1565 deserialization, leading zeros yield an error.
1566 - Not-a-number (NaN) values will be serialized to `null`.
1570 [RFC 7159](http://rfc7159.net/rfc7159) states:
1571 > This specification allows implementations to set limits on the range and
1572 > precision of numbers accepted. Since software that implements IEEE
1573 > 754-2008 binary64 (double precision) numbers is generally available and
1574 > widely used, good interoperability can be achieved by implementations
1575 > that expect no more precision or range than these provide, in the sense
1576 > that implementations will approximate JSON numbers within the expected
1579 This implementation does exactly follow this approach, as it uses double
1580 precision floating-point numbers. Note values smaller than
1581 `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
1582 will be stored as NaN internally and be serialized to `null`.
1586 Floating-point number values are stored directly inside a @ref basic_json
1589 @sa @ref number_integer_t -- type for number values (integer)
1591 @sa @ref number_unsigned_t -- type for number values (unsigned integer)
1593 @since version 1.0.0
1595 using number_float_t = NumberFloatType;
1601 /// helper for exception-safe object creation
1602 template<typename T, typename... Args>
1603 static T* create(Args&& ... args)
1605 AllocatorType<T> alloc;
1606 auto deleter = [&](T * object)
1608 alloc.deallocate(object, 1);
1610 std::unique_ptr<T, decltype(deleter)> object(alloc.allocate(1), deleter);
1611 alloc.construct(object.get(), std::forward<Args>(args)...);
1612 assert(object != nullptr);
1613 return object.release();
1616 ////////////////////////
1617 // JSON value storage //
1618 ////////////////////////
1623 The actual storage for a JSON value of the @ref basic_json class. This
1624 union combines the different storage types for the JSON value types
1625 defined in @ref value_t.
1627 JSON type | value_t type | used type
1628 --------- | --------------- | ------------------------
1629 object | object | pointer to @ref object_t
1630 array | array | pointer to @ref array_t
1631 string | string | pointer to @ref string_t
1632 boolean | boolean | @ref boolean_t
1633 number | number_integer | @ref number_integer_t
1634 number | number_unsigned | @ref number_unsigned_t
1635 number | number_float | @ref number_float_t
1636 null | null | *no value is stored*
1638 @note Variable-length types (objects, arrays, and strings) are stored as
1639 pointers. The size of the union should not exceed 64 bits if the default
1640 value types are used.
1642 @since version 1.0.0
1646 /// object (stored with pointer to save storage)
1648 /// array (stored with pointer to save storage)
1650 /// string (stored with pointer to save storage)
1654 /// number (integer)
1655 number_integer_t number_integer;
1656 /// number (unsigned integer)
1657 number_unsigned_t number_unsigned;
1658 /// number (floating-point)
1659 number_float_t number_float;
1661 /// default constructor (for null values)
1662 json_value() = default;
1663 /// constructor for booleans
1664 json_value(boolean_t v) noexcept : boolean(v) {}
1665 /// constructor for numbers (integer)
1666 json_value(number_integer_t v) noexcept : number_integer(v) {}
1667 /// constructor for numbers (unsigned)
1668 json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
1669 /// constructor for numbers (floating-point)
1670 json_value(number_float_t v) noexcept : number_float(v) {}
1671 /// constructor for empty values of a given type
1672 json_value(value_t t)
1676 case value_t::object:
1678 object = create<object_t>();
1682 case value_t::array:
1684 array = create<array_t>();
1688 case value_t::string:
1690 string = create<string_t>("");
1694 case value_t::boolean:
1696 boolean = boolean_t(false);
1700 case value_t::number_integer:
1702 number_integer = number_integer_t(0);
1706 case value_t::number_unsigned:
1708 number_unsigned = number_unsigned_t(0);
1712 case value_t::number_float:
1714 number_float = number_float_t(0.0);
1725 if (t == value_t::null)
1727 JSON_THROW(std::domain_error("961c151d2e87f2686a955a9be24d316f1362bf21 2.1.1")); // LCOV_EXCL_LINE
1734 /// constructor for strings
1735 json_value(const string_t& value)
1737 string = create<string_t>(value);
1740 /// constructor for objects
1741 json_value(const object_t& value)
1743 object = create<object_t>(value);
1746 /// constructor for arrays
1747 json_value(const array_t& value)
1749 array = create<array_t>(value);
1754 @brief checks the class invariants
1756 This function asserts the class invariants. It needs to be called at the
1757 end of every constructor to make sure that created objects respect the
1758 invariant. Furthermore, it has to be called each time the type of a JSON
1759 value is changed, because the invariant expresses a relationship between
1760 @a m_type and @a m_value.
1762 void assert_invariant() const
1764 assert(m_type != value_t::object or m_value.object != nullptr);
1765 assert(m_type != value_t::array or m_value.array != nullptr);
1766 assert(m_type != value_t::string or m_value.string != nullptr);
1770 //////////////////////////
1771 // JSON parser callback //
1772 //////////////////////////
1775 @brief JSON callback events
1777 This enumeration lists the parser events that can trigger calling a
1778 callback function of type @ref parser_callback_t during parsing.
1780 @image html callback_events.png "Example when certain parse events are triggered"
1782 @since version 1.0.0
1784 enum class parse_event_t : uint8_t
1786 /// the parser read `{` and started to process a JSON object
1788 /// the parser read `}` and finished processing a JSON object
1790 /// the parser read `[` and started to process a JSON array
1792 /// the parser read `]` and finished processing a JSON array
1794 /// the parser read a key of a value in an object
1796 /// the parser finished reading a JSON value
1801 @brief per-element parser callback type
1803 With a parser callback function, the result of parsing a JSON text can be
1804 influenced. When passed to @ref parse(std::istream&, const
1805 parser_callback_t) or @ref parse(const CharT, const parser_callback_t),
1806 it is called on certain events (passed as @ref parse_event_t via parameter
1807 @a event) with a set recursion depth @a depth and context JSON value
1808 @a parsed. The return value of the callback function is a boolean
1809 indicating whether the element that emitted the callback shall be kept or
1812 We distinguish six scenarios (determined by the event type) in which the
1813 callback function can be called. The following table describes the values
1814 of the parameters @a depth, @a event, and @a parsed.
1816 parameter @a event | description | parameter @a depth | parameter @a parsed
1817 ------------------ | ----------- | ------------------ | -------------------
1818 parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded
1819 parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key
1820 parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object
1821 parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded
1822 parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array
1823 parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
1825 @image html callback_events.png "Example when certain parse events are triggered"
1827 Discarding a value (i.e., returning `false`) has different effects
1828 depending on the context in which function was called:
1830 - Discarded values in structured types are skipped. That is, the parser
1831 will behave as if the discarded value was never read.
1832 - In case a value outside a structured type is skipped, it is replaced
1833 with `null`. This case happens if the top-level element is skipped.
1835 @param[in] depth the depth of the recursion during parsing
1837 @param[in] event an event of type parse_event_t indicating the context in
1838 the callback function has been called
1840 @param[in,out] parsed the current intermediate parse result; note that
1841 writing to this value has no effect for parse_event_t::key events
1843 @return Whether the JSON value which called the function during parsing
1844 should be kept (`true`) or not (`false`). In the latter case, it is either
1845 skipped completely or replaced by an empty discarded object.
1847 @sa @ref parse(std::istream&, parser_callback_t) or
1848 @ref parse(const CharT, const parser_callback_t) for examples
1850 @since version 1.0.0
1852 using parser_callback_t = std::function<bool(int depth,
1853 parse_event_t event,
1854 basic_json& parsed)>;
1861 /// @name constructors and destructors
1862 /// Constructors of class @ref basic_json, copy/move constructor, copy
1863 /// assignment, static functions creating objects, and the destructor.
1867 @brief create an empty value with a given type
1869 Create an empty JSON value with a given type. The value will be default
1870 initialized with an empty value which depends on the type:
1872 Value type | initial value
1873 ----------- | -------------
1881 @param[in] value_type the type of the value to create
1883 @complexity Constant.
1885 @throw std::bad_alloc if allocation for object, array, or string value
1888 @liveexample{The following code shows the constructor for different @ref
1889 value_t values,basic_json__value_t}
1891 @since version 1.0.0
1893 basic_json(const value_t value_type)
1894 : m_type(value_type), m_value(value_type)
1900 @brief create a null object
1902 Create a `null` JSON value. It either takes a null pointer as parameter
1903 (explicitly creating `null`) or no parameter (implicitly creating `null`).
1904 The passed null pointer itself is not read -- it is only used to choose
1905 the right constructor.
1907 @complexity Constant.
1909 @exceptionsafety No-throw guarantee: this constructor never throws
1912 @liveexample{The following code shows the constructor with and without a
1913 null pointer parameter.,basic_json__nullptr_t}
1915 @since version 1.0.0
1917 basic_json(std::nullptr_t = nullptr) noexcept
1918 : basic_json(value_t::null)
1924 @brief create a JSON value
1926 This is a "catch all" constructor for all compatible JSON types; that is,
1927 types for which a `to_json()` method exsits. The constructor forwards the
1928 parameter @a val to that method (to `json_serializer<U>::to_json` method
1929 with `U = uncvref_t<CompatibleType>`, to be exact).
1931 Template type @a CompatibleType includes, but is not limited to, the
1933 - **arrays**: @ref array_t and all kinds of compatible containers such as
1934 `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
1935 `std::array`, `std::set`, `std::unordered_set`, `std::multiset`, and
1936 `unordered_multiset` with a `value_type` from which a @ref basic_json
1937 value can be constructed.
1938 - **objects**: @ref object_t and all kinds of compatible associative
1939 containers such as `std::map`, `std::unordered_map`, `std::multimap`,
1940 and `std::unordered_multimap` with a `key_type` compatible to
1941 @ref string_t and a `value_type` from which a @ref basic_json value can
1943 - **strings**: @ref string_t, string literals, and all compatible string
1944 containers can be used.
1945 - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
1946 @ref number_float_t, and all convertible number types such as `int`,
1947 `size_t`, `int64_t`, `float` or `double` can be used.
1948 - **boolean**: @ref boolean_t / `bool` can be used.
1950 See the examples below.
1952 @tparam CompatibleType a type such that:
1953 - @a CompatibleType is not derived from `std::istream`,
1954 - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
1956 - @a CompatibleType is not a @ref basic_json nested type (e.g.,
1957 @ref json_pointer, @ref iterator, etc ...)
1958 - @ref @ref json_serializer<U> has a
1959 `to_json(basic_json_t&, CompatibleType&&)` method
1961 @tparam U = `uncvref_t<CompatibleType>`
1963 @param[in] val the value to be forwarded
1965 @complexity Usually linear in the size of the passed @a val, also
1966 depending on the implementation of the called `to_json()`
1969 @throw what `json_serializer<U>::to_json()` throws
1971 @liveexample{The following code shows the constructor with several
1972 compatible types.,basic_json__CompatibleType}
1974 @since version 2.1.0
1976 template<typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>,
1977 detail::enable_if_t<not std::is_base_of<std::istream, U>::value and
1978 not std::is_same<U, basic_json_t>::value and
1979 not detail::is_basic_json_nested_type<
1980 basic_json_t, U>::value and
1981 detail::has_to_json<basic_json, U>::value,
1983 basic_json(CompatibleType && val) noexcept(noexcept(JSONSerializer<U>::to_json(
1984 std::declval<basic_json_t&>(), std::forward<CompatibleType>(val))))
1986 JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
1991 @brief create a container (array or object) from an initializer list
1993 Creates a JSON value of type array or object from the passed initializer
1994 list @a init. In case @a type_deduction is `true` (default), the type of
1995 the JSON value to be created is deducted from the initializer list @a init
1996 according to the following rules:
1998 1. If the list is empty, an empty JSON object value `{}` is created.
1999 2. If the list consists of pairs whose first element is a string, a JSON
2000 object value is created where the first elements of the pairs are
2001 treated as keys and the second elements are as values.
2002 3. In all other cases, an array is created.
2004 The rules aim to create the best fit between a C++ initializer list and
2005 JSON values. The rationale is as follows:
2007 1. The empty initializer list is written as `{}` which is exactly an empty
2009 2. C++ has now way of describing mapped types other than to list a list of
2010 pairs. As JSON requires that keys must be of type string, rule 2 is the
2011 weakest constraint one can pose on initializer lists to interpret them
2013 3. In all other cases, the initializer list could not be interpreted as
2014 JSON object type, so interpreting it as JSON array type is safe.
2016 With the rules described above, the following JSON values cannot be
2017 expressed by an initializer list:
2019 - the empty array (`[]`): use @ref array(std::initializer_list<basic_json>)
2020 with an empty initializer list in this case
2021 - arrays whose elements satisfy rule 2: use @ref
2022 array(std::initializer_list<basic_json>) with the same initializer list
2025 @note When used without parentheses around an empty initializer list, @ref
2026 basic_json() is called instead of this function, yielding the JSON null
2029 @param[in] init initializer list with JSON values
2031 @param[in] type_deduction internal parameter; when set to `true`, the type
2032 of the JSON value is deducted from the initializer list @a init; when set
2033 to `false`, the type provided via @a manual_type is forced. This mode is
2034 used by the functions @ref array(std::initializer_list<basic_json>) and
2035 @ref object(std::initializer_list<basic_json>).
2037 @param[in] manual_type internal parameter; when @a type_deduction is set
2038 to `false`, the created JSON value will use the provided type (only @ref
2039 value_t::array and @ref value_t::object are valid); when @a type_deduction
2040 is set to `true`, this parameter has no effect
2042 @throw std::domain_error if @a type_deduction is `false`, @a manual_type
2043 is `value_t::object`, but @a init contains an element which is not a pair
2044 whose first element is a string; example: `"cannot create object from
2047 @complexity Linear in the size of the initializer list @a init.
2049 @liveexample{The example below shows how JSON values are created from
2050 initializer lists.,basic_json__list_init_t}
2052 @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array
2053 value from an initializer list
2054 @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object
2055 value from an initializer list
2057 @since version 1.0.0
2059 basic_json(std::initializer_list<basic_json> init,
2060 bool type_deduction = true,
2061 value_t manual_type = value_t::array)
2063 // check if each element is an array with two elements whose first
2064 // element is a string
2065 bool is_an_object = std::all_of(init.begin(), init.end(),
2066 [](const basic_json & element)
2068 return element.is_array() and element.size() == 2 and element[0].is_string();
2071 // adjust type if type deduction is not wanted
2072 if (not type_deduction)
2074 // if array is wanted, do not create an object though possible
2075 if (manual_type == value_t::array)
2077 is_an_object = false;
2080 // if object is wanted but impossible, throw an exception
2081 if (manual_type == value_t::object and not is_an_object)
2083 JSON_THROW(std::domain_error("cannot create object from initializer list"));
2089 // the initializer list is a list of pairs -> create object
2090 m_type = value_t::object;
2091 m_value = value_t::object;
2093 std::for_each(init.begin(), init.end(), [this](const basic_json & element)
2095 m_value.object->emplace(*(element[0].m_value.string), element[1]);
2100 // the initializer list describes an array -> create array
2101 m_type = value_t::array;
2102 m_value.array = create<array_t>(init);
2109 @brief explicitly create an array from an initializer list
2111 Creates a JSON array value from a given initializer list. That is, given a
2112 list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
2113 initializer list is empty, the empty array `[]` is created.
2115 @note This function is only needed to express two edge cases that cannot
2116 be realized with the initializer list constructor (@ref
2117 basic_json(std::initializer_list<basic_json>, bool, value_t)). These cases
2119 1. creating an array whose elements are all pairs whose first element is a
2120 string -- in this case, the initializer list constructor would create an
2121 object, taking the first elements as keys
2122 2. creating an empty array -- passing the empty initializer list to the
2123 initializer list constructor yields an empty object
2125 @param[in] init initializer list with JSON values to create an array from
2128 @return JSON array value
2130 @complexity Linear in the size of @a init.
2132 @liveexample{The following code shows an example for the `array`
2135 @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) --
2136 create a JSON value from an initializer list
2137 @sa @ref object(std::initializer_list<basic_json>) -- create a JSON object
2138 value from an initializer list
2140 @since version 1.0.0
2142 static basic_json array(std::initializer_list<basic_json> init =
2143 std::initializer_list<basic_json>())
2145 return basic_json(init, false, value_t::array);
2149 @brief explicitly create an object from an initializer list
2151 Creates a JSON object value from a given initializer list. The initializer
2152 lists elements must be pairs, and their first elements must be strings. If
2153 the initializer list is empty, the empty object `{}` is created.
2155 @note This function is only added for symmetry reasons. In contrast to the
2156 related function @ref array(std::initializer_list<basic_json>), there are
2157 no cases which can only be expressed by this function. That is, any
2158 initializer list @a init can also be passed to the initializer list
2159 constructor @ref basic_json(std::initializer_list<basic_json>, bool,
2162 @param[in] init initializer list to create an object from (optional)
2164 @return JSON object value
2166 @throw std::domain_error if @a init is not a pair whose first elements are
2168 @ref basic_json(std::initializer_list<basic_json>, bool, value_t)
2170 @complexity Linear in the size of @a init.
2172 @liveexample{The following code shows an example for the `object`
2175 @sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) --
2176 create a JSON value from an initializer list
2177 @sa @ref array(std::initializer_list<basic_json>) -- create a JSON array
2178 value from an initializer list
2180 @since version 1.0.0
2182 static basic_json object(std::initializer_list<basic_json> init =
2183 std::initializer_list<basic_json>())
2185 return basic_json(init, false, value_t::object);
2189 @brief construct an array with count copies of given value
2191 Constructs a JSON array value by creating @a cnt copies of a passed value.
2192 In case @a cnt is `0`, an empty array is created. As postcondition,
2193 `std::distance(begin(),end()) == cnt` holds.
2195 @param[in] cnt the number of JSON copies of @a val to create
2196 @param[in] val the JSON value to copy
2198 @complexity Linear in @a cnt.
2200 @liveexample{The following code shows examples for the @ref
2201 basic_json(size_type\, const basic_json&)
2202 constructor.,basic_json__size_type_basic_json}
2204 @since version 1.0.0
2206 basic_json(size_type cnt, const basic_json& val)
2207 : m_type(value_t::array)
2209 m_value.array = create<array_t>(cnt, val);
2214 @brief construct a JSON container given an iterator range
2216 Constructs the JSON value with the contents of the range `[first, last)`.
2217 The semantics depends on the different types a JSON value can have:
2218 - In case of primitive types (number, boolean, or string), @a first must
2219 be `begin()` and @a last must be `end()`. In this case, the value is
2220 copied. Otherwise, std::out_of_range is thrown.
2221 - In case of structured types (array, object), the constructor behaves as
2222 similar versions for `std::vector`.
2223 - In case of a null type, std::domain_error is thrown.
2225 @tparam InputIT an input iterator type (@ref iterator or @ref
2228 @param[in] first begin of the range to copy from (included)
2229 @param[in] last end of the range to copy from (excluded)
2231 @pre Iterators @a first and @a last must be initialized. **This
2232 precondition is enforced with an assertion.**
2234 @throw std::domain_error if iterators are not compatible; that is, do not
2235 belong to the same JSON value; example: `"iterators are not compatible"`
2236 @throw std::out_of_range if iterators are for a primitive type (number,
2237 boolean, or string) where an out of range error can be detected easily;
2238 example: `"iterators out of range"`
2239 @throw std::bad_alloc if allocation for object, array, or string fails
2240 @throw std::domain_error if called with a null value; example: `"cannot
2241 use construct with iterators from null"`
2243 @complexity Linear in distance between @a first and @a last.
2245 @liveexample{The example below shows several ways to create JSON values by
2246 specifying a subrange with iterators.,basic_json__InputIt_InputIt}
2248 @since version 1.0.0
2250 template<class InputIT, typename std::enable_if<
2251 std::is_same<InputIT, typename basic_json_t::iterator>::value or
2252 std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
2253 basic_json(InputIT first, InputIT last)
2255 assert(first.m_object != nullptr);
2256 assert(last.m_object != nullptr);
2258 // make sure iterator fits the current value
2259 if (first.m_object != last.m_object)
2261 JSON_THROW(std::domain_error("iterators are not compatible"));
2264 // copy type from first iterator
2265 m_type = first.m_object->m_type;
2267 // check if iterator range is complete for primitive values
2270 case value_t::boolean:
2271 case value_t::number_float:
2272 case value_t::number_integer:
2273 case value_t::number_unsigned:
2274 case value_t::string:
2276 if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())
2278 JSON_THROW(std::out_of_range("iterators out of range"));
2291 case value_t::number_integer:
2293 m_value.number_integer = first.m_object->m_value.number_integer;
2297 case value_t::number_unsigned:
2299 m_value.number_unsigned = first.m_object->m_value.number_unsigned;
2303 case value_t::number_float:
2305 m_value.number_float = first.m_object->m_value.number_float;
2309 case value_t::boolean:
2311 m_value.boolean = first.m_object->m_value.boolean;
2315 case value_t::string:
2317 m_value = *first.m_object->m_value.string;
2321 case value_t::object:
2323 m_value.object = create<object_t>(first.m_it.object_iterator,
2324 last.m_it.object_iterator);
2328 case value_t::array:
2330 m_value.array = create<array_t>(first.m_it.array_iterator,
2331 last.m_it.array_iterator);
2337 JSON_THROW(std::domain_error("cannot use construct with iterators from " + first.m_object->type_name()));
2345 @brief construct a JSON value given an input stream
2347 @param[in,out] i stream to read a serialized JSON value from
2348 @param[in] cb a parser callback function of type @ref parser_callback_t
2349 which is used to control the deserialization by filtering unwanted values
2352 @complexity Linear in the length of the input. The parser is a predictive
2353 LL(1) parser. The complexity can be higher if the parser callback function
2354 @a cb has a super-linear complexity.
2356 @note A UTF-8 byte order mark is silently ignored.
2358 @deprecated This constructor is deprecated and will be removed in version
2359 3.0.0 to unify the interface of the library. Deserialization will be
2360 done by stream operators or by calling one of the `parse` functions,
2361 e.g. @ref parse(std::istream&, const parser_callback_t). That is, calls
2362 like `json j(i);` for an input stream @a i need to be replaced by
2363 `json j = json::parse(i);`. See the example below.
2365 @liveexample{The example below demonstrates constructing a JSON value from
2366 a `std::stringstream` with and without callback
2367 function.,basic_json__istream}
2369 @since version 2.0.0, deprecated in version 2.0.3, to be removed in
2373 explicit basic_json(std::istream& i, const parser_callback_t cb = nullptr)
2375 *this = parser(i, cb).parse();
2379 ///////////////////////////////////////
2380 // other constructors and destructor //
2381 ///////////////////////////////////////
2384 @brief copy constructor
2386 Creates a copy of a given JSON value.
2388 @param[in] other the JSON value to copy
2390 @complexity Linear in the size of @a other.
2392 @requirement This function helps `basic_json` satisfying the
2393 [Container](http://en.cppreference.com/w/cpp/concept/Container)
2395 - The complexity is linear.
2396 - As postcondition, it holds: `other == basic_json(other)`.
2398 @throw std::bad_alloc if allocation for object, array, or string fails.
2400 @liveexample{The following code shows an example for the copy
2401 constructor.,basic_json__basic_json}
2403 @since version 1.0.0
2405 basic_json(const basic_json& other)
2406 : m_type(other.m_type)
2408 // check of passed value is valid
2409 other.assert_invariant();
2413 case value_t::object:
2415 m_value = *other.m_value.object;
2419 case value_t::array:
2421 m_value = *other.m_value.array;
2425 case value_t::string:
2427 m_value = *other.m_value.string;
2431 case value_t::boolean:
2433 m_value = other.m_value.boolean;
2437 case value_t::number_integer:
2439 m_value = other.m_value.number_integer;
2443 case value_t::number_unsigned:
2445 m_value = other.m_value.number_unsigned;
2449 case value_t::number_float:
2451 m_value = other.m_value.number_float;
2465 @brief move constructor
2467 Move constructor. Constructs a JSON value with the contents of the given
2468 value @a other using move semantics. It "steals" the resources from @a
2469 other and leaves it as JSON null value.
2471 @param[in,out] other value to move to this object
2473 @post @a other is a JSON null value
2475 @complexity Constant.
2477 @liveexample{The code below shows the move constructor explicitly called
2478 via std::move.,basic_json__moveconstructor}
2480 @since version 1.0.0
2482 basic_json(basic_json&& other) noexcept
2483 : m_type(std::move(other.m_type)),
2484 m_value(std::move(other.m_value))
2486 // check that passed value is valid
2487 other.assert_invariant();
2489 // invalidate payload
2490 other.m_type = value_t::null;
2497 @brief copy assignment
2499 Copy assignment operator. Copies a JSON value via the "copy and swap"
2500 strategy: It is expressed in terms of the copy constructor, destructor,
2501 and the swap() member function.
2503 @param[in] other value to copy from
2507 @requirement This function helps `basic_json` satisfying the
2508 [Container](http://en.cppreference.com/w/cpp/concept/Container)
2510 - The complexity is linear.
2512 @liveexample{The code below shows and example for the copy assignment. It
2513 creates a copy of value `a` which is then swapped with `b`. Finally\, the
2514 copy of `a` (which is the null value after the swap) is
2515 destroyed.,basic_json__copyassignment}
2517 @since version 1.0.0
2519 reference& operator=(basic_json other) noexcept (
2520 std::is_nothrow_move_constructible<value_t>::value and
2521 std::is_nothrow_move_assignable<value_t>::value and
2522 std::is_nothrow_move_constructible<json_value>::value and
2523 std::is_nothrow_move_assignable<json_value>::value
2526 // check that passed value is valid
2527 other.assert_invariant();
2530 swap(m_type, other.m_type);
2531 swap(m_value, other.m_value);
2540 Destroys the JSON value and frees all allocated memory.
2544 @requirement This function helps `basic_json` satisfying the
2545 [Container](http://en.cppreference.com/w/cpp/concept/Container)
2547 - The complexity is linear.
2548 - All stored elements are destroyed and all memory is freed.
2550 @since version 1.0.0
2558 case value_t::object:
2560 AllocatorType<object_t> alloc;
2561 alloc.destroy(m_value.object);
2562 alloc.deallocate(m_value.object, 1);
2566 case value_t::array:
2568 AllocatorType<array_t> alloc;
2569 alloc.destroy(m_value.array);
2570 alloc.deallocate(m_value.array, 1);
2574 case value_t::string:
2576 AllocatorType<string_t> alloc;
2577 alloc.destroy(m_value.string);
2578 alloc.deallocate(m_value.string, 1);
2584 // all other types need no specific destructor
2593 ///////////////////////
2594 // object inspection //
2595 ///////////////////////
2597 /// @name object inspection
2598 /// Functions to inspect the type of a JSON value.
2602 @brief serialization
2604 Serialization function for JSON values. The function tries to mimic
2605 Python's `json.dumps()` function, and currently supports its @a indent
2608 @param[in] indent If indent is nonnegative, then array elements and object
2609 members will be pretty-printed with that indent level. An indent level of
2610 `0` will only insert newlines. `-1` (the default) selects the most compact
2613 @return string containing the serialization of the JSON value
2617 @liveexample{The following example shows the effect of different @a indent
2618 parameters to the result of the serialization.,dump}
2620 @see https://docs.python.org/2/library/json.html#json.dump
2622 @since version 1.0.0
2624 string_t dump(const int indent = -1) const
2626 std::stringstream ss;
2630 dump(ss, true, static_cast<unsigned int>(indent));
2641 @brief return the type of the JSON value (explicit)
2643 Return the type of the JSON value as a value from the @ref value_t
2646 @return the type of the JSON value
2648 @complexity Constant.
2650 @exceptionsafety No-throw guarantee: this member function never throws
2653 @liveexample{The following code exemplifies `type()` for all JSON
2656 @since version 1.0.0
2658 constexpr value_t type() const noexcept
2664 @brief return whether type is primitive
2666 This function returns true iff the JSON type is primitive (string, number,
2669 @return `true` if type is primitive (string, number, boolean, or null),
2672 @complexity Constant.
2674 @exceptionsafety No-throw guarantee: this member function never throws
2677 @liveexample{The following code exemplifies `is_primitive()` for all JSON
2678 types.,is_primitive}
2680 @sa @ref is_structured() -- returns whether JSON value is structured
2681 @sa @ref is_null() -- returns whether JSON value is `null`
2682 @sa @ref is_string() -- returns whether JSON value is a string
2683 @sa @ref is_boolean() -- returns whether JSON value is a boolean
2684 @sa @ref is_number() -- returns whether JSON value is a number
2686 @since version 1.0.0
2688 constexpr bool is_primitive() const noexcept
2690 return is_null() or is_string() or is_boolean() or is_number();
2694 @brief return whether type is structured
2696 This function returns true iff the JSON type is structured (array or
2699 @return `true` if type is structured (array or object), `false` otherwise.
2701 @complexity Constant.
2703 @exceptionsafety No-throw guarantee: this member function never throws
2706 @liveexample{The following code exemplifies `is_structured()` for all JSON
2707 types.,is_structured}
2709 @sa @ref is_primitive() -- returns whether value is primitive
2710 @sa @ref is_array() -- returns whether value is an array
2711 @sa @ref is_object() -- returns whether value is an object
2713 @since version 1.0.0
2715 constexpr bool is_structured() const noexcept
2717 return is_array() or is_object();
2721 @brief return whether value is null
2723 This function returns true iff the JSON value is null.
2725 @return `true` if type is null, `false` otherwise.
2727 @complexity Constant.
2729 @exceptionsafety No-throw guarantee: this member function never throws
2732 @liveexample{The following code exemplifies `is_null()` for all JSON
2735 @since version 1.0.0
2737 constexpr bool is_null() const noexcept
2739 return m_type == value_t::null;
2743 @brief return whether value is a boolean
2745 This function returns true iff the JSON value is a boolean.
2747 @return `true` if type is boolean, `false` otherwise.
2749 @complexity Constant.
2751 @exceptionsafety No-throw guarantee: this member function never throws
2754 @liveexample{The following code exemplifies `is_boolean()` for all JSON
2757 @since version 1.0.0
2759 constexpr bool is_boolean() const noexcept
2761 return m_type == value_t::boolean;
2765 @brief return whether value is a number
2767 This function returns true iff the JSON value is a number. This includes
2768 both integer and floating-point values.
2770 @return `true` if type is number (regardless whether integer, unsigned
2771 integer or floating-type), `false` otherwise.
2773 @complexity Constant.
2775 @exceptionsafety No-throw guarantee: this member function never throws
2778 @liveexample{The following code exemplifies `is_number()` for all JSON
2781 @sa @ref is_number_integer() -- check if value is an integer or unsigned
2783 @sa @ref is_number_unsigned() -- check if value is an unsigned integer
2785 @sa @ref is_number_float() -- check if value is a floating-point number
2787 @since version 1.0.0
2789 constexpr bool is_number() const noexcept
2791 return is_number_integer() or is_number_float();
2795 @brief return whether value is an integer number
2797 This function returns true iff the JSON value is an integer or unsigned
2798 integer number. This excludes floating-point values.
2800 @return `true` if type is an integer or unsigned integer number, `false`
2803 @complexity Constant.
2805 @exceptionsafety No-throw guarantee: this member function never throws
2808 @liveexample{The following code exemplifies `is_number_integer()` for all
2809 JSON types.,is_number_integer}
2811 @sa @ref is_number() -- check if value is a number
2812 @sa @ref is_number_unsigned() -- check if value is an unsigned integer
2814 @sa @ref is_number_float() -- check if value is a floating-point number
2816 @since version 1.0.0
2818 constexpr bool is_number_integer() const noexcept
2820 return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
2824 @brief return whether value is an unsigned integer number
2826 This function returns true iff the JSON value is an unsigned integer
2827 number. This excludes floating-point and (signed) integer values.
2829 @return `true` if type is an unsigned integer number, `false` otherwise.
2831 @complexity Constant.
2833 @exceptionsafety No-throw guarantee: this member function never throws
2836 @liveexample{The following code exemplifies `is_number_unsigned()` for all
2837 JSON types.,is_number_unsigned}
2839 @sa @ref is_number() -- check if value is a number
2840 @sa @ref is_number_integer() -- check if value is an integer or unsigned
2842 @sa @ref is_number_float() -- check if value is a floating-point number
2844 @since version 2.0.0
2846 constexpr bool is_number_unsigned() const noexcept
2848 return m_type == value_t::number_unsigned;
2852 @brief return whether value is a floating-point number
2854 This function returns true iff the JSON value is a floating-point number.
2855 This excludes integer and unsigned integer values.
2857 @return `true` if type is a floating-point number, `false` otherwise.
2859 @complexity Constant.
2861 @exceptionsafety No-throw guarantee: this member function never throws
2864 @liveexample{The following code exemplifies `is_number_float()` for all
2865 JSON types.,is_number_float}
2867 @sa @ref is_number() -- check if value is number
2868 @sa @ref is_number_integer() -- check if value is an integer number
2869 @sa @ref is_number_unsigned() -- check if value is an unsigned integer
2872 @since version 1.0.0
2874 constexpr bool is_number_float() const noexcept
2876 return m_type == value_t::number_float;
2880 @brief return whether value is an object
2882 This function returns true iff the JSON value is an object.
2884 @return `true` if type is object, `false` otherwise.
2886 @complexity Constant.
2888 @exceptionsafety No-throw guarantee: this member function never throws
2891 @liveexample{The following code exemplifies `is_object()` for all JSON
2894 @since version 1.0.0
2896 constexpr bool is_object() const noexcept
2898 return m_type == value_t::object;
2902 @brief return whether value is an array
2904 This function returns true iff the JSON value is an array.
2906 @return `true` if type is array, `false` otherwise.
2908 @complexity Constant.
2910 @exceptionsafety No-throw guarantee: this member function never throws
2913 @liveexample{The following code exemplifies `is_array()` for all JSON
2916 @since version 1.0.0
2918 constexpr bool is_array() const noexcept
2920 return m_type == value_t::array;
2924 @brief return whether value is a string
2926 This function returns true iff the JSON value is a string.
2928 @return `true` if type is string, `false` otherwise.
2930 @complexity Constant.
2932 @exceptionsafety No-throw guarantee: this member function never throws
2935 @liveexample{The following code exemplifies `is_string()` for all JSON
2938 @since version 1.0.0
2940 constexpr bool is_string() const noexcept
2942 return m_type == value_t::string;
2946 @brief return whether value is discarded
2948 This function returns true iff the JSON value was discarded during parsing
2949 with a callback function (see @ref parser_callback_t).
2951 @note This function will always be `false` for JSON values after parsing.
2952 That is, discarded values can only occur during parsing, but will be
2953 removed when inside a structured value or replaced by null in other cases.
2955 @return `true` if type is discarded, `false` otherwise.
2957 @complexity Constant.
2959 @exceptionsafety No-throw guarantee: this member function never throws
2962 @liveexample{The following code exemplifies `is_discarded()` for all JSON
2963 types.,is_discarded}
2965 @since version 1.0.0
2967 constexpr bool is_discarded() const noexcept
2969 return m_type == value_t::discarded;
2973 @brief return the type of the JSON value (implicit)
2975 Implicitly return the type of the JSON value as a value from the @ref
2976 value_t enumeration.
2978 @return the type of the JSON value
2980 @complexity Constant.
2982 @exceptionsafety No-throw guarantee: this member function never throws
2985 @liveexample{The following code exemplifies the @ref value_t operator for
2986 all JSON types.,operator__value_t}
2988 @since version 1.0.0
2990 constexpr operator value_t() const noexcept
3002 /// get a boolean (explicit)
3003 boolean_t get_impl(boolean_t* /*unused*/) const
3007 return m_value.boolean;
3010 JSON_THROW(std::domain_error("type must be boolean, but is " + type_name()));
3013 /// get a pointer to the value (object)
3014 object_t* get_impl_ptr(object_t* /*unused*/) noexcept
3016 return is_object() ? m_value.object : nullptr;
3019 /// get a pointer to the value (object)
3020 constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
3022 return is_object() ? m_value.object : nullptr;
3025 /// get a pointer to the value (array)
3026 array_t* get_impl_ptr(array_t* /*unused*/) noexcept
3028 return is_array() ? m_value.array : nullptr;
3031 /// get a pointer to the value (array)
3032 constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
3034 return is_array() ? m_value.array : nullptr;
3037 /// get a pointer to the value (string)
3038 string_t* get_impl_ptr(string_t* /*unused*/) noexcept
3040 return is_string() ? m_value.string : nullptr;
3043 /// get a pointer to the value (string)
3044 constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
3046 return is_string() ? m_value.string : nullptr;
3049 /// get a pointer to the value (boolean)
3050 boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
3052 return is_boolean() ? &m_value.boolean : nullptr;
3055 /// get a pointer to the value (boolean)
3056 constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
3058 return is_boolean() ? &m_value.boolean : nullptr;
3061 /// get a pointer to the value (integer number)
3062 number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
3064 return is_number_integer() ? &m_value.number_integer : nullptr;
3067 /// get a pointer to the value (integer number)
3068 constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
3070 return is_number_integer() ? &m_value.number_integer : nullptr;
3073 /// get a pointer to the value (unsigned number)
3074 number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
3076 return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
3079 /// get a pointer to the value (unsigned number)
3080 constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
3082 return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
3085 /// get a pointer to the value (floating-point number)
3086 number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
3088 return is_number_float() ? &m_value.number_float : nullptr;
3091 /// get a pointer to the value (floating-point number)
3092 constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
3094 return is_number_float() ? &m_value.number_float : nullptr;
3098 @brief helper function to implement get_ref()
3100 This funcion helps to implement get_ref() without code duplication for
3101 const and non-const overloads
3103 @tparam ThisType will be deduced as `basic_json` or `const basic_json`
3105 @throw std::domain_error if ReferenceType does not match underlying value
3106 type of the current JSON
3108 template<typename ReferenceType, typename ThisType>
3109 static ReferenceType get_ref_impl(ThisType& obj)
3112 using PointerType = typename std::add_pointer<ReferenceType>::type;
3114 // delegate the call to get_ptr<>()
3115 auto ptr = obj.template get_ptr<PointerType>();
3122 JSON_THROW(std::domain_error("incompatible ReferenceType for get_ref, actual type is " +
3127 /// @name value access
3128 /// Direct access to the stored value of a JSON value.
3132 @brief get special-case overload
3134 This overloads avoids a lot of template boilerplate, it can be seen as the
3137 @tparam BasicJsonType == @ref basic_json
3139 @return a copy of *this
3141 @complexity Constant.
3143 @since version 2.1.0
3146 typename BasicJsonType,
3147 detail::enable_if_t<std::is_same<typename std::remove_const<BasicJsonType>::type,
3148 basic_json_t>::value,
3150 basic_json get() const
3156 @brief get a value (explicit)
3158 Explicit type conversion between the JSON value and a compatible value
3159 which is [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
3160 and [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
3161 The value is converted by calling the @ref json_serializer<ValueType>
3162 `from_json()` method.
3164 The function is equivalent to executing
3167 JSONSerializer<ValueType>::from_json(*this, ret);
3171 This overloads is chosen if:
3172 - @a ValueType is not @ref basic_json,
3173 - @ref json_serializer<ValueType> has a `from_json()` method of the form
3174 `void from_json(const @ref basic_json&, ValueType&)`, and
3175 - @ref json_serializer<ValueType> does not have a `from_json()` method of
3176 the form `ValueType from_json(const @ref basic_json&)`
3178 @tparam ValueTypeCV the provided value type
3179 @tparam ValueType the returned value type
3181 @return copy of the JSON value, converted to @a ValueType
3183 @throw what @ref json_serializer<ValueType> `from_json()` method throws
3185 @liveexample{The example below shows several conversions from JSON values
3186 to other types. There a few things to note: (1) Floating-point numbers can
3187 be converted to integers\, (2) A JSON array can be converted to a standard
3188 `std::vector<short>`\, (3) A JSON object can be converted to C++
3189 associative containers such as `std::unordered_map<std::string\,
3190 json>`.,get__ValueType_const}
3192 @since version 2.1.0
3195 typename ValueTypeCV,
3196 typename ValueType = detail::uncvref_t<ValueTypeCV>,
3197 detail::enable_if_t <
3198 not std::is_same<basic_json_t, ValueType>::value and
3199 detail::has_from_json<basic_json_t, ValueType>::value and
3200 not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
3202 ValueType get() const noexcept(noexcept(
3203 JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
3205 // we cannot static_assert on ValueTypeCV being non-const, because
3206 // there is support for get<const basic_json_t>(), which is why we
3207 // still need the uncvref
3208 static_assert(not std::is_reference<ValueTypeCV>::value,
3209 "get() cannot be used with reference types, you might want to use get_ref()");
3210 static_assert(std::is_default_constructible<ValueType>::value,
3211 "types must be DefaultConstructible when used with get()");
3214 JSONSerializer<ValueType>::from_json(*this, ret);
3219 @brief get a value (explicit); special case
3221 Explicit type conversion between the JSON value and a compatible value
3222 which is **not** [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible)
3223 and **not** [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible).
3224 The value is converted by calling the @ref json_serializer<ValueType>
3225 `from_json()` method.
3227 The function is equivalent to executing
3229 return JSONSerializer<ValueTypeCV>::from_json(*this);
3232 This overloads is chosen if:
3233 - @a ValueType is not @ref basic_json and
3234 - @ref json_serializer<ValueType> has a `from_json()` method of the form
3235 `ValueType from_json(const @ref basic_json&)`
3237 @note If @ref json_serializer<ValueType> has both overloads of
3238 `from_json()`, this one is chosen.
3240 @tparam ValueTypeCV the provided value type
3241 @tparam ValueType the returned value type
3243 @return copy of the JSON value, converted to @a ValueType
3245 @throw what @ref json_serializer<ValueType> `from_json()` method throws
3247 @since version 2.1.0
3250 typename ValueTypeCV,
3251 typename ValueType = detail::uncvref_t<ValueTypeCV>,
3252 detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
3253 detail::has_non_default_from_json<basic_json_t,
3254 ValueType>::value, int> = 0 >
3255 ValueType get() const noexcept(noexcept(
3256 JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>())))
3258 static_assert(not std::is_reference<ValueTypeCV>::value,
3259 "get() cannot be used with reference types, you might want to use get_ref()");
3260 return JSONSerializer<ValueTypeCV>::from_json(*this);
3264 @brief get a pointer value (explicit)
3266 Explicit pointer access to the internally stored JSON value. No copies are
3269 @warning The pointer becomes invalid if the underlying JSON object
3272 @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
3273 object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
3274 @ref number_unsigned_t, or @ref number_float_t.
3276 @return pointer to the internally stored JSON value if the requested
3277 pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
3279 @complexity Constant.
3281 @liveexample{The example below shows how pointers to internal values of a
3282 JSON value can be requested. Note that no type conversions are made and a
3283 `nullptr` is returned if the value and the requested pointer type does not
3284 match.,get__PointerType}
3286 @sa @ref get_ptr() for explicit pointer-member access
3288 @since version 1.0.0
3290 template<typename PointerType, typename std::enable_if<
3291 std::is_pointer<PointerType>::value, int>::type = 0>
3292 PointerType get() noexcept
3294 // delegate the call to get_ptr
3295 return get_ptr<PointerType>();
3299 @brief get a pointer value (explicit)
3302 template<typename PointerType, typename std::enable_if<
3303 std::is_pointer<PointerType>::value, int>::type = 0>
3304 constexpr const PointerType get() const noexcept
3306 // delegate the call to get_ptr
3307 return get_ptr<PointerType>();
3311 @brief get a pointer value (implicit)
3313 Implicit pointer access to the internally stored JSON value. No copies are
3316 @warning Writing data to the pointee of the result yields an undefined
3319 @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
3320 object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
3321 @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
3324 @return pointer to the internally stored JSON value if the requested
3325 pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
3327 @complexity Constant.
3329 @liveexample{The example below shows how pointers to internal values of a
3330 JSON value can be requested. Note that no type conversions are made and a
3331 `nullptr` is returned if the value and the requested pointer type does not
3334 @since version 1.0.0
3336 template<typename PointerType, typename std::enable_if<
3337 std::is_pointer<PointerType>::value, int>::type = 0>
3338 PointerType get_ptr() noexcept
3340 // get the type of the PointerType (remove pointer and const)
3341 using pointee_t = typename std::remove_const<typename
3342 std::remove_pointer<typename
3343 std::remove_const<PointerType>::type>::type>::type;
3344 // make sure the type matches the allowed types
3346 std::is_same<object_t, pointee_t>::value
3347 or std::is_same<array_t, pointee_t>::value
3348 or std::is_same<string_t, pointee_t>::value
3349 or std::is_same<boolean_t, pointee_t>::value
3350 or std::is_same<number_integer_t, pointee_t>::value
3351 or std::is_same<number_unsigned_t, pointee_t>::value
3352 or std::is_same<number_float_t, pointee_t>::value
3353 , "incompatible pointer type");
3355 // delegate the call to get_impl_ptr<>()
3356 return get_impl_ptr(static_cast<PointerType>(nullptr));
3360 @brief get a pointer value (implicit)
3363 template<typename PointerType, typename std::enable_if<
3364 std::is_pointer<PointerType>::value and
3365 std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
3366 constexpr const PointerType get_ptr() const noexcept
3368 // get the type of the PointerType (remove pointer and const)
3369 using pointee_t = typename std::remove_const<typename
3370 std::remove_pointer<typename
3371 std::remove_const<PointerType>::type>::type>::type;
3372 // make sure the type matches the allowed types
3374 std::is_same<object_t, pointee_t>::value
3375 or std::is_same<array_t, pointee_t>::value
3376 or std::is_same<string_t, pointee_t>::value
3377 or std::is_same<boolean_t, pointee_t>::value
3378 or std::is_same<number_integer_t, pointee_t>::value
3379 or std::is_same<number_unsigned_t, pointee_t>::value
3380 or std::is_same<number_float_t, pointee_t>::value
3381 , "incompatible pointer type");
3383 // delegate the call to get_impl_ptr<>() const
3384 return get_impl_ptr(static_cast<const PointerType>(nullptr));
3388 @brief get a reference value (implicit)
3390 Implicit reference access to the internally stored JSON value. No copies
3393 @warning Writing data to the referee of the result yields an undefined
3396 @tparam ReferenceType reference type; must be a reference to @ref array_t,
3397 @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
3398 @ref number_float_t. Enforced by static assertion.
3400 @return reference to the internally stored JSON value if the requested
3401 reference type @a ReferenceType fits to the JSON value; throws
3402 std::domain_error otherwise
3404 @throw std::domain_error in case passed type @a ReferenceType is
3405 incompatible with the stored JSON value
3407 @complexity Constant.
3409 @liveexample{The example shows several calls to `get_ref()`.,get_ref}
3411 @since version 1.1.0
3413 template<typename ReferenceType, typename std::enable_if<
3414 std::is_reference<ReferenceType>::value, int>::type = 0>
3415 ReferenceType get_ref()
3417 // delegate call to get_ref_impl
3418 return get_ref_impl<ReferenceType>(*this);
3422 @brief get a reference value (implicit)
3425 template<typename ReferenceType, typename std::enable_if<
3426 std::is_reference<ReferenceType>::value and
3427 std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
3428 ReferenceType get_ref() const
3430 // delegate call to get_ref_impl
3431 return get_ref_impl<ReferenceType>(*this);
3435 @brief get a value (implicit)
3437 Implicit type conversion between the JSON value and a compatible value.
3438 The call is realized by calling @ref get() const.
3440 @tparam ValueType non-pointer type compatible to the JSON value, for
3441 instance `int` for JSON integer numbers, `bool` for JSON booleans, or
3442 `std::vector` types for JSON arrays. The character type of @ref string_t
3443 as well as an initializer list of this type is excluded to avoid
3444 ambiguities as these types implicitly convert to `std::string`.
3446 @return copy of the JSON value, converted to type @a ValueType
3448 @throw std::domain_error in case passed type @a ValueType is incompatible
3449 to JSON, thrown by @ref get() const
3451 @complexity Linear in the size of the JSON value.
3453 @liveexample{The example below shows several conversions from JSON values
3454 to other types. There a few things to note: (1) Floating-point numbers can
3455 be converted to integers\, (2) A JSON array can be converted to a standard
3456 `std::vector<short>`\, (3) A JSON object can be converted to C++
3457 associative containers such as `std::unordered_map<std::string\,
3458 json>`.,operator__ValueType}
3460 @since version 1.0.0
3462 template < typename ValueType, typename std::enable_if <
3463 not std::is_pointer<ValueType>::value and
3464 not std::is_same<ValueType, typename string_t::value_type>::value
3465 #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
3466 and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
3469 operator ValueType() const
3471 // delegate the call to get<>() const
3472 return get<ValueType>();
3478 ////////////////////
3479 // element access //
3480 ////////////////////
3482 /// @name element access
3483 /// Access to the JSON value.
3487 @brief access specified array element with bounds checking
3489 Returns a reference to the element at specified location @a idx, with
3492 @param[in] idx index of the element to access
3494 @return reference to the element at index @a idx
3496 @throw std::domain_error if the JSON value is not an array; example:
3497 `"cannot use at() with string"`
3498 @throw std::out_of_range if the index @a idx is out of range of the array;
3499 that is, `idx >= size()`; example: `"array index 7 is out of range"`
3501 @complexity Constant.
3503 @liveexample{The example below shows how array elements can be read and
3504 written using `at()`.,at__size_type}
3506 @since version 1.0.0
3508 reference at(size_type idx)
3510 // at only works for arrays
3515 return m_value.array->at(idx);
3517 JSON_CATCH (std::out_of_range&)
3519 // create better exception explanation
3520 JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range"));
3525 JSON_THROW(std::domain_error("cannot use at() with " + type_name()));
3530 @brief access specified array element with bounds checking
3532 Returns a const reference to the element at specified location @a idx,
3533 with bounds checking.
3535 @param[in] idx index of the element to access
3537 @return const reference to the element at index @a idx
3539 @throw std::domain_error if the JSON value is not an array; example:
3540 `"cannot use at() with string"`
3541 @throw std::out_of_range if the index @a idx is out of range of the array;
3542 that is, `idx >= size()`; example: `"array index 7 is out of range"`
3544 @complexity Constant.
3546 @liveexample{The example below shows how array elements can be read using
3547 `at()`.,at__size_type_const}
3549 @since version 1.0.0
3551 const_reference at(size_type idx) const
3553 // at only works for arrays
3558 return m_value.array->at(idx);
3560 JSON_CATCH (std::out_of_range&)
3562 // create better exception explanation
3563 JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range"));
3568 JSON_THROW(std::domain_error("cannot use at() with " + type_name()));
3573 @brief access specified object element with bounds checking
3575 Returns a reference to the element at with specified key @a key, with
3578 @param[in] key key of the element to access
3580 @return reference to the element at key @a key
3582 @throw std::domain_error if the JSON value is not an object; example:
3583 `"cannot use at() with boolean"`
3584 @throw std::out_of_range if the key @a key is is not stored in the object;
3585 that is, `find(key) == end()`; example: `"key "the fast" not found"`
3587 @complexity Logarithmic in the size of the container.
3589 @liveexample{The example below shows how object elements can be read and
3590 written using `at()`.,at__object_t_key_type}
3592 @sa @ref operator[](const typename object_t::key_type&) for unchecked
3594 @sa @ref value() for access by value with a default value
3596 @since version 1.0.0
3598 reference at(const typename object_t::key_type& key)
3600 // at only works for objects
3605 return m_value.object->at(key);
3607 JSON_CATCH (std::out_of_range&)
3609 // create better exception explanation
3610 JSON_THROW(std::out_of_range("key '" + key + "' not found"));
3615 JSON_THROW(std::domain_error("cannot use at() with " + type_name()));
3620 @brief access specified object element with bounds checking
3622 Returns a const reference to the element at with specified key @a key,
3623 with bounds checking.
3625 @param[in] key key of the element to access
3627 @return const reference to the element at key @a key
3629 @throw std::domain_error if the JSON value is not an object; example:
3630 `"cannot use at() with boolean"`
3631 @throw std::out_of_range if the key @a key is is not stored in the object;
3632 that is, `find(key) == end()`; example: `"key "the fast" not found"`
3634 @complexity Logarithmic in the size of the container.
3636 @liveexample{The example below shows how object elements can be read using
3637 `at()`.,at__object_t_key_type_const}
3639 @sa @ref operator[](const typename object_t::key_type&) for unchecked
3641 @sa @ref value() for access by value with a default value
3643 @since version 1.0.0
3645 const_reference at(const typename object_t::key_type& key) const
3647 // at only works for objects
3652 return m_value.object->at(key);
3654 JSON_CATCH (std::out_of_range&)
3656 // create better exception explanation
3657 JSON_THROW(std::out_of_range("key '" + key + "' not found"));
3662 JSON_THROW(std::domain_error("cannot use at() with " + type_name()));
3667 @brief access specified array element
3669 Returns a reference to the element at specified location @a idx.
3671 @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
3672 then the array is silently filled up with `null` values to make `idx` a
3673 valid reference to the last stored element.
3675 @param[in] idx index of the element to access
3677 @return reference to the element at index @a idx
3679 @throw std::domain_error if JSON is not an array or null; example:
3680 `"cannot use operator[] with string"`
3682 @complexity Constant if @a idx is in the range of the array. Otherwise
3683 linear in `idx - size()`.
3685 @liveexample{The example below shows how array elements can be read and
3686 written using `[]` operator. Note the addition of `null`
3687 values.,operatorarray__size_type}
3689 @since version 1.0.0
3691 reference operator[](size_type idx)
3693 // implicitly convert null value to an empty array
3696 m_type = value_t::array;
3697 m_value.array = create<array_t>();
3701 // operator[] only works for arrays
3704 // fill up array with null values if given idx is outside range
3705 if (idx >= m_value.array->size())
3707 m_value.array->insert(m_value.array->end(),
3708 idx - m_value.array->size() + 1,
3712 return m_value.array->operator[](idx);
3715 JSON_THROW(std::domain_error("cannot use operator[] with " + type_name()));
3719 @brief access specified array element
3721 Returns a const reference to the element at specified location @a idx.
3723 @param[in] idx index of the element to access
3725 @return const reference to the element at index @a idx
3727 @throw std::domain_error if JSON is not an array; example: `"cannot use
3728 operator[] with null"`
3730 @complexity Constant.
3732 @liveexample{The example below shows how array elements can be read using
3733 the `[]` operator.,operatorarray__size_type_const}
3735 @since version 1.0.0
3737 const_reference operator[](size_type idx) const
3739 // const operator[] only works for arrays
3742 return m_value.array->operator[](idx);
3745 JSON_THROW(std::domain_error("cannot use operator[] with " + type_name()));
3749 @brief access specified object element
3751 Returns a reference to the element at with specified key @a key.
3753 @note If @a key is not found in the object, then it is silently added to
3754 the object and filled with a `null` value to make `key` a valid reference.
3755 In case the value was `null` before, it is converted to an object.
3757 @param[in] key key of the element to access
3759 @return reference to the element at key @a key
3761 @throw std::domain_error if JSON is not an object or null; example:
3762 `"cannot use operator[] with string"`
3764 @complexity Logarithmic in the size of the container.
3766 @liveexample{The example below shows how object elements can be read and
3767 written using the `[]` operator.,operatorarray__key_type}
3769 @sa @ref at(const typename object_t::key_type&) for access by reference
3771 @sa @ref value() for access by value with a default value
3773 @since version 1.0.0
3775 reference operator[](const typename object_t::key_type& key)
3777 // implicitly convert null value to an empty object
3780 m_type = value_t::object;
3781 m_value.object = create<object_t>();
3785 // operator[] only works for objects
3788 return m_value.object->operator[](key);
3791 JSON_THROW(std::domain_error("cannot use operator[] with " + type_name()));
3795 @brief read-only access specified object element
3797 Returns a const reference to the element at with specified key @a key. No
3798 bounds checking is performed.
3800 @warning If the element with key @a key does not exist, the behavior is
3803 @param[in] key key of the element to access
3805 @return const reference to the element at key @a key
3807 @pre The element with key @a key must exist. **This precondition is
3808 enforced with an assertion.**
3810 @throw std::domain_error if JSON is not an object; example: `"cannot use
3811 operator[] with null"`
3813 @complexity Logarithmic in the size of the container.
3815 @liveexample{The example below shows how object elements can be read using
3816 the `[]` operator.,operatorarray__key_type_const}
3818 @sa @ref at(const typename object_t::key_type&) for access by reference
3820 @sa @ref value() for access by value with a default value
3822 @since version 1.0.0
3824 const_reference operator[](const typename object_t::key_type& key) const
3826 // const operator[] only works for objects
3829 assert(m_value.object->find(key) != m_value.object->end());
3830 return m_value.object->find(key)->second;
3833 JSON_THROW(std::domain_error("cannot use operator[] with " + type_name()));
3837 @brief access specified object element
3839 Returns a reference to the element at with specified key @a key.
3841 @note If @a key is not found in the object, then it is silently added to
3842 the object and filled with a `null` value to make `key` a valid reference.
3843 In case the value was `null` before, it is converted to an object.
3845 @param[in] key key of the element to access
3847 @return reference to the element at key @a key
3849 @throw std::domain_error if JSON is not an object or null; example:
3850 `"cannot use operator[] with string"`
3852 @complexity Logarithmic in the size of the container.
3854 @liveexample{The example below shows how object elements can be read and
3855 written using the `[]` operator.,operatorarray__key_type}
3857 @sa @ref at(const typename object_t::key_type&) for access by reference
3859 @sa @ref value() for access by value with a default value
3861 @since version 1.0.0
3863 template<typename T, std::size_t n>
3864 reference operator[](T * (&key)[n])
3866 return operator[](static_cast<const T>(key));
3870 @brief read-only access specified object element
3872 Returns a const reference to the element at with specified key @a key. No
3873 bounds checking is performed.
3875 @warning If the element with key @a key does not exist, the behavior is
3878 @note This function is required for compatibility reasons with Clang.
3880 @param[in] key key of the element to access
3882 @return const reference to the element at key @a key
3884 @throw std::domain_error if JSON is not an object; example: `"cannot use
3885 operator[] with null"`
3887 @complexity Logarithmic in the size of the container.
3889 @liveexample{The example below shows how object elements can be read using
3890 the `[]` operator.,operatorarray__key_type_const}
3892 @sa @ref at(const typename object_t::key_type&) for access by reference
3894 @sa @ref value() for access by value with a default value
3896 @since version 1.0.0
3898 template<typename T, std::size_t n>
3899 const_reference operator[](T * (&key)[n]) const
3901 return operator[](static_cast<const T>(key));
3905 @brief access specified object element
3907 Returns a reference to the element at with specified key @a key.
3909 @note If @a key is not found in the object, then it is silently added to
3910 the object and filled with a `null` value to make `key` a valid reference.
3911 In case the value was `null` before, it is converted to an object.
3913 @param[in] key key of the element to access
3915 @return reference to the element at key @a key
3917 @throw std::domain_error if JSON is not an object or null; example:
3918 `"cannot use operator[] with string"`
3920 @complexity Logarithmic in the size of the container.
3922 @liveexample{The example below shows how object elements can be read and
3923 written using the `[]` operator.,operatorarray__key_type}
3925 @sa @ref at(const typename object_t::key_type&) for access by reference
3927 @sa @ref value() for access by value with a default value
3929 @since version 1.1.0
3931 template<typename T>
3932 reference operator[](T* key)
3934 // implicitly convert null to object
3937 m_type = value_t::object;
3938 m_value = value_t::object;
3942 // at only works for objects
3945 return m_value.object->operator[](key);
3948 JSON_THROW(std::domain_error("cannot use operator[] with " + type_name()));
3952 @brief read-only access specified object element
3954 Returns a const reference to the element at with specified key @a key. No
3955 bounds checking is performed.
3957 @warning If the element with key @a key does not exist, the behavior is
3960 @param[in] key key of the element to access
3962 @return const reference to the element at key @a key
3964 @pre The element with key @a key must exist. **This precondition is
3965 enforced with an assertion.**
3967 @throw std::domain_error if JSON is not an object; example: `"cannot use
3968 operator[] with null"`
3970 @complexity Logarithmic in the size of the container.
3972 @liveexample{The example below shows how object elements can be read using
3973 the `[]` operator.,operatorarray__key_type_const}
3975 @sa @ref at(const typename object_t::key_type&) for access by reference
3977 @sa @ref value() for access by value with a default value
3979 @since version 1.1.0
3981 template<typename T>
3982 const_reference operator[](T* key) const
3984 // at only works for objects
3987 assert(m_value.object->find(key) != m_value.object->end());
3988 return m_value.object->find(key)->second;
3991 JSON_THROW(std::domain_error("cannot use operator[] with " + type_name()));
3995 @brief access specified object element with default value
3997 Returns either a copy of an object's element at the specified key @a key
3998 or a given default value if no element with key @a key exists.
4000 The function is basically equivalent to executing
4004 } catch(std::out_of_range) {
4005 return default_value;
4009 @note Unlike @ref at(const typename object_t::key_type&), this function
4010 does not throw if the given key @a key was not found.
4012 @note Unlike @ref operator[](const typename object_t::key_type& key), this
4013 function does not implicitly add an element to the position defined by @a
4014 key. This function is furthermore also applicable to const objects.
4016 @param[in] key key of the element to access
4017 @param[in] default_value the value to return if @a key is not found
4019 @tparam ValueType type compatible to JSON values, for instance `int` for
4020 JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
4021 JSON arrays. Note the type of the expected value at @a key and the default
4022 value @a default_value must be compatible.
4024 @return copy of the element at key @a key or @a default_value if @a key
4027 @throw std::domain_error if JSON is not an object; example: `"cannot use
4030 @complexity Logarithmic in the size of the container.
4032 @liveexample{The example below shows how object elements can be queried
4033 with a default value.,basic_json__value}
4035 @sa @ref at(const typename object_t::key_type&) for access by reference
4037 @sa @ref operator[](const typename object_t::key_type&) for unchecked
4040 @since version 1.0.0
4042 template<class ValueType, typename std::enable_if<
4043 std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
4044 ValueType value(const typename object_t::key_type& key, ValueType default_value) const
4046 // at only works for objects
4049 // if key is found, return value and given default value otherwise
4050 const auto it = find(key);
4056 return default_value;
4060 JSON_THROW(std::domain_error("cannot use value() with " + type_name()));
4065 @brief overload for a default value of type const char*
4066 @copydoc basic_json::value(const typename object_t::key_type&, ValueType) const
4068 string_t value(const typename object_t::key_type& key, const char* default_value) const
4070 return value(key, string_t(default_value));
4074 @brief access specified object element via JSON Pointer with default value
4076 Returns either a copy of an object's element at the specified key @a key
4077 or a given default value if no element with key @a key exists.
4079 The function is basically equivalent to executing
4083 } catch(std::out_of_range) {
4084 return default_value;
4088 @note Unlike @ref at(const json_pointer&), this function does not throw
4089 if the given key @a key was not found.
4091 @param[in] ptr a JSON pointer to the element to access
4092 @param[in] default_value the value to return if @a ptr found no value
4094 @tparam ValueType type compatible to JSON values, for instance `int` for
4095 JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
4096 JSON arrays. Note the type of the expected value at @a key and the default
4097 value @a default_value must be compatible.
4099 @return copy of the element at key @a key or @a default_value if @a key
4102 @throw std::domain_error if JSON is not an object; example: `"cannot use
4105 @complexity Logarithmic in the size of the container.
4107 @liveexample{The example below shows how object elements can be queried
4108 with a default value.,basic_json__value_ptr}
4110 @sa @ref operator[](const json_pointer&) for unchecked access by reference
4112 @since version 2.0.2
4114 template<class ValueType, typename std::enable_if<
4115 std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
4116 ValueType value(const json_pointer& ptr, ValueType default_value) const
4118 // at only works for objects
4121 // if pointer resolves a value, return it or use default value
4124 return ptr.get_checked(this);
4126 JSON_CATCH (std::out_of_range&)
4128 return default_value;
4132 JSON_THROW(std::domain_error("cannot use value() with " + type_name()));
4136 @brief overload for a default value of type const char*
4137 @copydoc basic_json::value(const json_pointer&, ValueType) const
4139 string_t value(const json_pointer& ptr, const char* default_value) const
4141 return value(ptr, string_t(default_value));
4145 @brief access the first element
4147 Returns a reference to the first element in the container. For a JSON
4148 container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
4150 @return In case of a structured type (array or object), a reference to the
4151 first element is returned. In case of number, string, or boolean values, a
4152 reference to the value is returned.
4154 @complexity Constant.
4156 @pre The JSON value must not be `null` (would throw `std::out_of_range`)
4157 or an empty array or object (undefined behavior, **guarded by
4159 @post The JSON value remains unchanged.
4161 @throw std::out_of_range when called on `null` value
4163 @liveexample{The following code shows an example for `front()`.,front}
4165 @sa @ref back() -- access the last element
4167 @since version 1.0.0
4175 @copydoc basic_json::front()
4177 const_reference front() const
4183 @brief access the last element
4185 Returns a reference to the last element in the container. For a JSON
4186 container `c`, the expression `c.back()` is equivalent to
4193 @return In case of a structured type (array or object), a reference to the
4194 last element is returned. In case of number, string, or boolean values, a
4195 reference to the value is returned.
4197 @complexity Constant.
4199 @pre The JSON value must not be `null` (would throw `std::out_of_range`)
4200 or an empty array or object (undefined behavior, **guarded by
4202 @post The JSON value remains unchanged.
4204 @throw std::out_of_range when called on `null` value.
4206 @liveexample{The following code shows an example for `back()`.,back}
4208 @sa @ref front() -- access the first element
4210 @since version 1.0.0
4220 @copydoc basic_json::back()
4222 const_reference back() const
4230 @brief remove element given an iterator
4232 Removes the element specified by iterator @a pos. The iterator @a pos must
4233 be valid and dereferenceable. Thus the `end()` iterator (which is valid,
4234 but is not dereferenceable) cannot be used as a value for @a pos.
4236 If called on a primitive type other than `null`, the resulting JSON value
4239 @param[in] pos iterator to the element to remove
4240 @return Iterator following the last removed element. If the iterator @a
4241 pos refers to the last element, the `end()` iterator is returned.
4243 @tparam IteratorType an @ref iterator or @ref const_iterator
4245 @post Invalidates iterators and references at or after the point of the
4246 erase, including the `end()` iterator.
4248 @throw std::domain_error if called on a `null` value; example: `"cannot
4249 use erase() with null"`
4250 @throw std::domain_error if called on an iterator which does not belong to
4251 the current JSON value; example: `"iterator does not fit current value"`
4252 @throw std::out_of_range if called on a primitive type with invalid
4253 iterator (i.e., any iterator which is not `begin()`); example: `"iterator
4256 @complexity The complexity depends on the type:
4257 - objects: amortized constant
4258 - arrays: linear in distance between @a pos and the end of the container
4259 - strings: linear in the length of the string
4260 - other types: constant
4262 @liveexample{The example shows the result of `erase()` for different JSON
4263 types.,erase__IteratorType}
4265 @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
4267 @sa @ref erase(const typename object_t::key_type&) -- removes the element
4268 from an object at the given key
4269 @sa @ref erase(const size_type) -- removes the element from an array at
4272 @since version 1.0.0
4274 template<class IteratorType, typename std::enable_if<
4275 std::is_same<IteratorType, typename basic_json_t::iterator>::value or
4276 std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
4278 IteratorType erase(IteratorType pos)
4280 // make sure iterator fits the current value
4281 if (this != pos.m_object)
4283 JSON_THROW(std::domain_error("iterator does not fit current value"));
4286 IteratorType result = end();
4290 case value_t::boolean:
4291 case value_t::number_float:
4292 case value_t::number_integer:
4293 case value_t::number_unsigned:
4294 case value_t::string:
4296 if (not pos.m_it.primitive_iterator.is_begin())
4298 JSON_THROW(std::out_of_range("iterator out of range"));
4303 AllocatorType<string_t> alloc;
4304 alloc.destroy(m_value.string);
4305 alloc.deallocate(m_value.string, 1);
4306 m_value.string = nullptr;
4309 m_type = value_t::null;
4314 case value_t::object:
4316 result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
4320 case value_t::array:
4322 result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
4328 JSON_THROW(std::domain_error("cannot use erase() with " + type_name()));
4336 @brief remove elements given an iterator range
4338 Removes the element specified by the range `[first; last)`. The iterator
4339 @a first does not need to be dereferenceable if `first == last`: erasing
4340 an empty range is a no-op.
4342 If called on a primitive type other than `null`, the resulting JSON value
4345 @param[in] first iterator to the beginning of the range to remove
4346 @param[in] last iterator past the end of the range to remove
4347 @return Iterator following the last removed element. If the iterator @a
4348 second refers to the last element, the `end()` iterator is returned.
4350 @tparam IteratorType an @ref iterator or @ref const_iterator
4352 @post Invalidates iterators and references at or after the point of the
4353 erase, including the `end()` iterator.
4355 @throw std::domain_error if called on a `null` value; example: `"cannot
4356 use erase() with null"`
4357 @throw std::domain_error if called on iterators which does not belong to
4358 the current JSON value; example: `"iterators do not fit current value"`
4359 @throw std::out_of_range if called on a primitive type with invalid
4360 iterators (i.e., if `first != begin()` and `last != end()`); example:
4361 `"iterators out of range"`
4363 @complexity The complexity depends on the type:
4364 - objects: `log(size()) + std::distance(first, last)`
4365 - arrays: linear in the distance between @a first and @a last, plus linear
4366 in the distance between @a last and end of the container
4367 - strings: linear in the length of the string
4368 - other types: constant
4370 @liveexample{The example shows the result of `erase()` for different JSON
4371 types.,erase__IteratorType_IteratorType}
4373 @sa @ref erase(IteratorType) -- removes the element at a given position
4374 @sa @ref erase(const typename object_t::key_type&) -- removes the element
4375 from an object at the given key
4376 @sa @ref erase(const size_type) -- removes the element from an array at
4379 @since version 1.0.0
4381 template<class IteratorType, typename std::enable_if<
4382 std::is_same<IteratorType, typename basic_json_t::iterator>::value or
4383 std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
4385 IteratorType erase(IteratorType first, IteratorType last)
4387 // make sure iterator fits the current value
4388 if (this != first.m_object or this != last.m_object)
4390 JSON_THROW(std::domain_error("iterators do not fit current value"));
4393 IteratorType result = end();
4397 case value_t::boolean:
4398 case value_t::number_float:
4399 case value_t::number_integer:
4400 case value_t::number_unsigned:
4401 case value_t::string:
4403 if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())
4405 JSON_THROW(std::out_of_range("iterators out of range"));
4410 AllocatorType<string_t> alloc;
4411 alloc.destroy(m_value.string);
4412 alloc.deallocate(m_value.string, 1);
4413 m_value.string = nullptr;
4416 m_type = value_t::null;
4421 case value_t::object:
4423 result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
4424 last.m_it.object_iterator);
4428 case value_t::array:
4430 result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
4431 last.m_it.array_iterator);
4437 JSON_THROW(std::domain_error("cannot use erase() with " + type_name()));
4445 @brief remove element from a JSON object given a key
4447 Removes elements from a JSON object with the key value @a key.
4449 @param[in] key value of the elements to remove
4451 @return Number of elements removed. If @a ObjectType is the default
4452 `std::map` type, the return value will always be `0` (@a key was not
4453 found) or `1` (@a key was found).
4455 @post References and iterators to the erased elements are invalidated.
4456 Other references and iterators are not affected.
4458 @throw std::domain_error when called on a type other than JSON object;
4459 example: `"cannot use erase() with null"`
4461 @complexity `log(size()) + count(key)`
4463 @liveexample{The example shows the effect of `erase()`.,erase__key_type}
4465 @sa @ref erase(IteratorType) -- removes the element at a given position
4466 @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
4468 @sa @ref erase(const size_type) -- removes the element from an array at
4471 @since version 1.0.0
4473 size_type erase(const typename object_t::key_type& key)
4475 // this erase only works for objects
4478 return m_value.object->erase(key);
4481 JSON_THROW(std::domain_error("cannot use erase() with " + type_name()));
4485 @brief remove element from a JSON array given an index
4487 Removes element from a JSON array at the index @a idx.
4489 @param[in] idx index of the element to remove
4491 @throw std::domain_error when called on a type other than JSON array;
4492 example: `"cannot use erase() with null"`
4493 @throw std::out_of_range when `idx >= size()`; example: `"array index 17
4496 @complexity Linear in distance between @a idx and the end of the container.
4498 @liveexample{The example shows the effect of `erase()`.,erase__size_type}
4500 @sa @ref erase(IteratorType) -- removes the element at a given position
4501 @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
4503 @sa @ref erase(const typename object_t::key_type&) -- removes the element
4504 from an object at the given key
4506 @since version 1.0.0
4508 void erase(const size_type idx)
4510 // this erase only works for arrays
4515 JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range"));
4518 m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
4522 JSON_THROW(std::domain_error("cannot use erase() with " + type_name()));
4537 @brief find an element in a JSON object
4539 Finds an element in a JSON object with key equivalent to @a key. If the
4540 element is not found or the JSON value is not an object, end() is
4543 @note This method always returns @ref end() when executed on a JSON type
4544 that is not an object.
4546 @param[in] key key value of the element to search for
4548 @return Iterator to an element with key equivalent to @a key. If no such
4549 element is found or the JSON value is not an object, past-the-end (see
4550 @ref end()) iterator is returned.
4552 @complexity Logarithmic in the size of the JSON object.
4554 @liveexample{The example shows how `find()` is used.,find__key_type}
4556 @since version 1.0.0
4558 iterator find(typename object_t::key_type key)
4560 auto result = end();
4564 result.m_it.object_iterator = m_value.object->find(key);
4571 @brief find an element in a JSON object
4572 @copydoc find(typename object_t::key_type)
4574 const_iterator find(typename object_t::key_type key) const
4576 auto result = cend();
4580 result.m_it.object_iterator = m_value.object->find(key);
4587 @brief returns the number of occurrences of a key in a JSON object
4589 Returns the number of elements with key @a key. If ObjectType is the
4590 default `std::map` type, the return value will always be `0` (@a key was
4591 not found) or `1` (@a key was found).
4593 @note This method always returns `0` when executed on a JSON type that is
4596 @param[in] key key value of the element to count
4598 @return Number of elements with key @a key. If the JSON value is not an
4599 object, the return value will be `0`.
4601 @complexity Logarithmic in the size of the JSON object.
4603 @liveexample{The example shows how `count()` is used.,count}
4605 @since version 1.0.0
4607 size_type count(typename object_t::key_type key) const
4609 // return 0 for all nonobject types
4610 return is_object() ? m_value.object->count(key) : 0;
4624 @brief returns an iterator to the first element
4626 Returns an iterator to the first element.
4628 @image html range-begin-end.svg "Illustration from cppreference.com"
4630 @return iterator to the first element
4632 @complexity Constant.
4634 @requirement This function helps `basic_json` satisfying the
4635 [Container](http://en.cppreference.com/w/cpp/concept/Container)
4637 - The complexity is constant.
4639 @liveexample{The following code shows an example for `begin()`.,begin}
4641 @sa @ref cbegin() -- returns a const iterator to the beginning
4642 @sa @ref end() -- returns an iterator to the end
4643 @sa @ref cend() -- returns a const iterator to the end
4645 @since version 1.0.0
4647 iterator begin() noexcept
4649 iterator result(this);
4655 @copydoc basic_json::cbegin()
4657 const_iterator begin() const noexcept
4663 @brief returns a const iterator to the first element
4665 Returns a const iterator to the first element.
4667 @image html range-begin-end.svg "Illustration from cppreference.com"
4669 @return const iterator to the first element
4671 @complexity Constant.
4673 @requirement This function helps `basic_json` satisfying the
4674 [Container](http://en.cppreference.com/w/cpp/concept/Container)
4676 - The complexity is constant.
4677 - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
4679 @liveexample{The following code shows an example for `cbegin()`.,cbegin}
4681 @sa @ref begin() -- returns an iterator to the beginning
4682 @sa @ref end() -- returns an iterator to the end
4683 @sa @ref cend() -- returns a const iterator to the end
4685 @since version 1.0.0
4687 const_iterator cbegin() const noexcept
4689 const_iterator result(this);
4695 @brief returns an iterator to one past the last element
4697 Returns an iterator to one past the last element.
4699 @image html range-begin-end.svg "Illustration from cppreference.com"
4701 @return iterator one past the last element
4703 @complexity Constant.
4705 @requirement This function helps `basic_json` satisfying the
4706 [Container](http://en.cppreference.com/w/cpp/concept/Container)
4708 - The complexity is constant.
4710 @liveexample{The following code shows an example for `end()`.,end}
4712 @sa @ref cend() -- returns a const iterator to the end
4713 @sa @ref begin() -- returns an iterator to the beginning
4714 @sa @ref cbegin() -- returns a const iterator to the beginning
4716 @since version 1.0.0
4718 iterator end() noexcept
4720 iterator result(this);
4726 @copydoc basic_json::cend()
4728 const_iterator end() const noexcept
4734 @brief returns a const iterator to one past the last element
4736 Returns a const iterator to one past the last element.
4738 @image html range-begin-end.svg "Illustration from cppreference.com"
4740 @return const iterator one past the last element
4742 @complexity Constant.
4744 @requirement This function helps `basic_json` satisfying the
4745 [Container](http://en.cppreference.com/w/cpp/concept/Container)
4747 - The complexity is constant.
4748 - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
4750 @liveexample{The following code shows an example for `cend()`.,cend}
4752 @sa @ref end() -- returns an iterator to the end
4753 @sa @ref begin() -- returns an iterator to the beginning
4754 @sa @ref cbegin() -- returns a const iterator to the beginning
4756 @since version 1.0.0
4758 const_iterator cend() const noexcept
4760 const_iterator result(this);
4766 @brief returns an iterator to the reverse-beginning
4768 Returns an iterator to the reverse-beginning; that is, the last element.
4770 @image html range-rbegin-rend.svg "Illustration from cppreference.com"
4772 @complexity Constant.
4774 @requirement This function helps `basic_json` satisfying the
4775 [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
4777 - The complexity is constant.
4778 - Has the semantics of `reverse_iterator(end())`.
4780 @liveexample{The following code shows an example for `rbegin()`.,rbegin}
4782 @sa @ref crbegin() -- returns a const reverse iterator to the beginning
4783 @sa @ref rend() -- returns a reverse iterator to the end
4784 @sa @ref crend() -- returns a const reverse iterator to the end
4786 @since version 1.0.0
4788 reverse_iterator rbegin() noexcept
4790 return reverse_iterator(end());
4794 @copydoc basic_json::crbegin()
4796 const_reverse_iterator rbegin() const noexcept
4802 @brief returns an iterator to the reverse-end
4804 Returns an iterator to the reverse-end; that is, one before the first
4807 @image html range-rbegin-rend.svg "Illustration from cppreference.com"
4809 @complexity Constant.
4811 @requirement This function helps `basic_json` satisfying the
4812 [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
4814 - The complexity is constant.
4815 - Has the semantics of `reverse_iterator(begin())`.
4817 @liveexample{The following code shows an example for `rend()`.,rend}
4819 @sa @ref crend() -- returns a const reverse iterator to the end
4820 @sa @ref rbegin() -- returns a reverse iterator to the beginning
4821 @sa @ref crbegin() -- returns a const reverse iterator to the beginning
4823 @since version 1.0.0
4825 reverse_iterator rend() noexcept
4827 return reverse_iterator(begin());
4831 @copydoc basic_json::crend()
4833 const_reverse_iterator rend() const noexcept
4839 @brief returns a const reverse iterator to the last element
4841 Returns a const iterator to the reverse-beginning; that is, the last
4844 @image html range-rbegin-rend.svg "Illustration from cppreference.com"
4846 @complexity Constant.
4848 @requirement This function helps `basic_json` satisfying the
4849 [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
4851 - The complexity is constant.
4852 - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
4854 @liveexample{The following code shows an example for `crbegin()`.,crbegin}
4856 @sa @ref rbegin() -- returns a reverse iterator to the beginning
4857 @sa @ref rend() -- returns a reverse iterator to the end
4858 @sa @ref crend() -- returns a const reverse iterator to the end
4860 @since version 1.0.0
4862 const_reverse_iterator crbegin() const noexcept
4864 return const_reverse_iterator(cend());
4868 @brief returns a const reverse iterator to one before the first
4870 Returns a const reverse iterator to the reverse-end; that is, one before
4873 @image html range-rbegin-rend.svg "Illustration from cppreference.com"
4875 @complexity Constant.
4877 @requirement This function helps `basic_json` satisfying the
4878 [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer)
4880 - The complexity is constant.
4881 - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
4883 @liveexample{The following code shows an example for `crend()`.,crend}
4885 @sa @ref rend() -- returns a reverse iterator to the end
4886 @sa @ref rbegin() -- returns a reverse iterator to the beginning
4887 @sa @ref crbegin() -- returns a const reverse iterator to the beginning
4889 @since version 1.0.0
4891 const_reverse_iterator crend() const noexcept
4893 return const_reverse_iterator(cbegin());
4897 // forward declaration
4898 template<typename IteratorType> class iteration_proxy;
4902 @brief wrapper to access iterator member functions in range-based for
4904 This function allows to access @ref iterator::key() and @ref
4905 iterator::value() during range-based for loops. In these loops, a
4906 reference to the JSON values is returned, so there is no access to the
4907 underlying iterator.
4909 @note The name of this function is not yet final and may change in the
4912 static iteration_proxy<iterator> iterator_wrapper(reference cont)
4914 return iteration_proxy<iterator>(cont);
4918 @copydoc iterator_wrapper(reference)
4920 static iteration_proxy<const_iterator> iterator_wrapper(const_reference cont)
4922 return iteration_proxy<const_iterator>(cont);
4936 @brief checks whether the container is empty
4938 Checks if a JSON value has no elements.
4940 @return The return value depends on the different types and is
4942 Value type | return value
4943 ----------- | -------------
4948 object | result of function `object_t::empty()`
4949 array | result of function `array_t::empty()`
4951 @note This function does not return whether a string stored as JSON value
4952 is empty - it returns whether the JSON container itself is empty which is
4953 false in the case of a string.
4955 @complexity Constant, as long as @ref array_t and @ref object_t satisfy
4956 the Container concept; that is, their `empty()` functions have constant
4959 @requirement This function helps `basic_json` satisfying the
4960 [Container](http://en.cppreference.com/w/cpp/concept/Container)
4962 - The complexity is constant.
4963 - Has the semantics of `begin() == end()`.
4965 @liveexample{The following code uses `empty()` to check if a JSON
4966 object contains any elements.,empty}
4968 @sa @ref size() -- returns the number of elements
4970 @since version 1.0.0
4972 bool empty() const noexcept
4978 // null values are empty
4982 case value_t::array:
4984 // delegate call to array_t::empty()
4985 return m_value.array->empty();
4988 case value_t::object:
4990 // delegate call to object_t::empty()
4991 return m_value.object->empty();
4996 // all other types are nonempty
5003 @brief returns the number of elements
5005 Returns the number of elements in a JSON value.
5007 @return The return value depends on the different types and is
5009 Value type | return value
5010 ----------- | -------------
5015 object | result of function object_t::size()
5016 array | result of function array_t::size()
5018 @note This function does not return the length of a string stored as JSON
5019 value - it returns the number of elements in the JSON value which is 1 in
5020 the case of a string.
5022 @complexity Constant, as long as @ref array_t and @ref object_t satisfy
5023 the Container concept; that is, their size() functions have constant
5026 @requirement This function helps `basic_json` satisfying the
5027 [Container](http://en.cppreference.com/w/cpp/concept/Container)
5029 - The complexity is constant.
5030 - Has the semantics of `std::distance(begin(), end())`.
5032 @liveexample{The following code calls `size()` on the different value
5035 @sa @ref empty() -- checks whether the container is empty
5036 @sa @ref max_size() -- returns the maximal number of elements
5038 @since version 1.0.0
5040 size_type size() const noexcept
5046 // null values are empty
5050 case value_t::array:
5052 // delegate call to array_t::size()
5053 return m_value.array->size();
5056 case value_t::object:
5058 // delegate call to object_t::size()
5059 return m_value.object->size();
5064 // all other types have size 1
5071 @brief returns the maximum possible number of elements
5073 Returns the maximum number of elements a JSON value is able to hold due to
5074 system or library implementation limitations, i.e. `std::distance(begin(),
5075 end())` for the JSON value.
5077 @return The return value depends on the different types and is
5079 Value type | return value
5080 ----------- | -------------
5081 null | `0` (same as `size()`)
5082 boolean | `1` (same as `size()`)
5083 string | `1` (same as `size()`)
5084 number | `1` (same as `size()`)
5085 object | result of function `object_t::max_size()`
5086 array | result of function `array_t::max_size()`
5088 @complexity Constant, as long as @ref array_t and @ref object_t satisfy
5089 the Container concept; that is, their `max_size()` functions have constant
5092 @requirement This function helps `basic_json` satisfying the
5093 [Container](http://en.cppreference.com/w/cpp/concept/Container)
5095 - The complexity is constant.
5096 - Has the semantics of returning `b.size()` where `b` is the largest
5097 possible JSON value.
5099 @liveexample{The following code calls `max_size()` on the different value
5100 types. Note the output is implementation specific.,max_size}
5102 @sa @ref size() -- returns the number of elements
5104 @since version 1.0.0
5106 size_type max_size() const noexcept
5110 case value_t::array:
5112 // delegate call to array_t::max_size()
5113 return m_value.array->max_size();
5116 case value_t::object:
5118 // delegate call to object_t::max_size()
5119 return m_value.object->max_size();
5124 // all other types have max_size() == size()
5141 @brief clears the contents
5143 Clears the content of a JSON value and resets it to the default value as
5144 if @ref basic_json(value_t) would have been called:
5146 Value type | initial value
5147 ----------- | -------------
5155 @complexity Linear in the size of the JSON value.
5157 @liveexample{The example below shows the effect of `clear()` to different
5160 @since version 1.0.0
5162 void clear() noexcept
5166 case value_t::number_integer:
5168 m_value.number_integer = 0;
5172 case value_t::number_unsigned:
5174 m_value.number_unsigned = 0;
5178 case value_t::number_float:
5180 m_value.number_float = 0.0;
5184 case value_t::boolean:
5186 m_value.boolean = false;
5190 case value_t::string:
5192 m_value.string->clear();
5196 case value_t::array:
5198 m_value.array->clear();
5202 case value_t::object:
5204 m_value.object->clear();
5216 @brief add an object to an array
5218 Appends the given element @a val to the end of the JSON value. If the
5219 function is called on a JSON null value, an empty array is created before
5222 @param[in] val the value to add to the JSON array
5224 @throw std::domain_error when called on a type other than JSON array or
5225 null; example: `"cannot use push_back() with number"`
5227 @complexity Amortized constant.
5229 @liveexample{The example shows how `push_back()` and `+=` can be used to
5230 add elements to a JSON array. Note how the `null` value was silently
5231 converted to a JSON array.,push_back}
5233 @since version 1.0.0
5235 void push_back(basic_json&& val)
5237 // push_back only works for null objects or arrays
5238 if (not(is_null() or is_array()))
5240 JSON_THROW(std::domain_error("cannot use push_back() with " + type_name()));
5243 // transform null object into an array
5246 m_type = value_t::array;
5247 m_value = value_t::array;
5251 // add element to array (move semantics)
5252 m_value.array->push_back(std::move(val));
5253 // invalidate object
5254 val.m_type = value_t::null;
5258 @brief add an object to an array
5259 @copydoc push_back(basic_json&&)
5261 reference operator+=(basic_json&& val)
5263 push_back(std::move(val));
5268 @brief add an object to an array
5269 @copydoc push_back(basic_json&&)
5271 void push_back(const basic_json& val)
5273 // push_back only works for null objects or arrays
5274 if (not(is_null() or is_array()))
5276 JSON_THROW(std::domain_error("cannot use push_back() with " + type_name()));
5279 // transform null object into an array
5282 m_type = value_t::array;
5283 m_value = value_t::array;
5287 // add element to array
5288 m_value.array->push_back(val);
5292 @brief add an object to an array
5293 @copydoc push_back(basic_json&&)
5295 reference operator+=(const basic_json& val)
5302 @brief add an object to an object
5304 Inserts the given element @a val to the JSON object. If the function is
5305 called on a JSON null value, an empty object is created before inserting
5308 @param[in] val the value to add to the JSON object
5310 @throw std::domain_error when called on a type other than JSON object or
5311 null; example: `"cannot use push_back() with number"`
5313 @complexity Logarithmic in the size of the container, O(log(`size()`)).
5315 @liveexample{The example shows how `push_back()` and `+=` can be used to
5316 add elements to a JSON object. Note how the `null` value was silently
5317 converted to a JSON object.,push_back__object_t__value}
5319 @since version 1.0.0
5321 void push_back(const typename object_t::value_type& val)
5323 // push_back only works for null objects or objects
5324 if (not(is_null() or is_object()))
5326 JSON_THROW(std::domain_error("cannot use push_back() with " + type_name()));
5329 // transform null object into an object
5332 m_type = value_t::object;
5333 m_value = value_t::object;
5337 // add element to array
5338 m_value.object->insert(val);
5342 @brief add an object to an object
5343 @copydoc push_back(const typename object_t::value_type&)
5345 reference operator+=(const typename object_t::value_type& val)
5352 @brief add an object to an object
5354 This function allows to use `push_back` with an initializer list. In case
5356 1. the current value is an object,
5357 2. the initializer list @a init contains only two elements, and
5358 3. the first element of @a init is a string,
5360 @a init is converted into an object element and added using
5361 @ref push_back(const typename object_t::value_type&). Otherwise, @a init
5362 is converted to a JSON value and added using @ref push_back(basic_json&&).
5364 @param init an initializer list
5366 @complexity Linear in the size of the initializer list @a init.
5368 @note This function is required to resolve an ambiguous overload error,
5369 because pairs like `{"key", "value"}` can be both interpreted as
5370 `object_t::value_type` or `std::initializer_list<basic_json>`, see
5371 https://github.com/nlohmann/json/issues/235 for more information.
5373 @liveexample{The example shows how initializer lists are treated as
5374 objects when possible.,push_back__initializer_list}
5376 void push_back(std::initializer_list<basic_json> init)
5378 if (is_object() and init.size() == 2 and init.begin()->is_string())
5380 const string_t key = *init.begin();
5381 push_back(typename object_t::value_type(key, *(init.begin() + 1)));
5385 push_back(basic_json(init));
5390 @brief add an object to an object
5391 @copydoc push_back(std::initializer_list<basic_json>)
5393 reference operator+=(std::initializer_list<basic_json> init)
5400 @brief add an object to an array
5402 Creates a JSON value from the passed parameters @a args to the end of the
5403 JSON value. If the function is called on a JSON null value, an empty array
5404 is created before appending the value created from @a args.
5406 @param[in] args arguments to forward to a constructor of @ref basic_json
5407 @tparam Args compatible types to create a @ref basic_json object
5409 @throw std::domain_error when called on a type other than JSON array or
5410 null; example: `"cannot use emplace_back() with number"`
5412 @complexity Amortized constant.
5414 @liveexample{The example shows how `push_back()` can be used to add
5415 elements to a JSON array. Note how the `null` value was silently converted
5416 to a JSON array.,emplace_back}
5418 @since version 2.0.8
5420 template<class... Args>
5421 void emplace_back(Args&& ... args)
5423 // emplace_back only works for null objects or arrays
5424 if (not(is_null() or is_array()))
5426 JSON_THROW(std::domain_error("cannot use emplace_back() with " + type_name()));
5429 // transform null object into an array
5432 m_type = value_t::array;
5433 m_value = value_t::array;
5437 // add element to array (perfect forwarding)
5438 m_value.array->emplace_back(std::forward<Args>(args)...);
5442 @brief add an object to an object if key does not exist
5444 Inserts a new element into a JSON object constructed in-place with the
5445 given @a args if there is no element with the key in the container. If the
5446 function is called on a JSON null value, an empty object is created before
5447 appending the value created from @a args.
5449 @param[in] args arguments to forward to a constructor of @ref basic_json
5450 @tparam Args compatible types to create a @ref basic_json object
5452 @return a pair consisting of an iterator to the inserted element, or the
5453 already-existing element if no insertion happened, and a bool
5454 denoting whether the insertion took place.
5456 @throw std::domain_error when called on a type other than JSON object or
5457 null; example: `"cannot use emplace() with number"`
5459 @complexity Logarithmic in the size of the container, O(log(`size()`)).
5461 @liveexample{The example shows how `emplace()` can be used to add elements
5462 to a JSON object. Note how the `null` value was silently converted to a
5463 JSON object. Further note how no value is added if there was already one
5464 value stored with the same key.,emplace}
5466 @since version 2.0.8
5468 template<class... Args>
5469 std::pair<iterator, bool> emplace(Args&& ... args)
5471 // emplace only works for null objects or arrays
5472 if (not(is_null() or is_object()))
5474 JSON_THROW(std::domain_error("cannot use emplace() with " + type_name()));
5477 // transform null object into an object
5480 m_type = value_t::object;
5481 m_value = value_t::object;
5485 // add element to array (perfect forwarding)
5486 auto res = m_value.object->emplace(std::forward<Args>(args)...);
5487 // create result iterator and set iterator to the result of emplace
5489 it.m_it.object_iterator = res.first;
5491 // return pair of iterator and boolean
5492 return {it, res.second};
5496 @brief inserts element
5498 Inserts element @a val before iterator @a pos.
5500 @param[in] pos iterator before which the content will be inserted; may be
5502 @param[in] val element to insert
5503 @return iterator pointing to the inserted @a val.
5505 @throw std::domain_error if called on JSON values other than arrays;
5506 example: `"cannot use insert() with string"`
5507 @throw std::domain_error if @a pos is not an iterator of *this; example:
5508 `"iterator does not fit current value"`
5510 @complexity Constant plus linear in the distance between @a pos and end of
5513 @liveexample{The example shows how `insert()` is used.,insert}
5515 @since version 1.0.0
5517 iterator insert(const_iterator pos, const basic_json& val)
5519 // insert only works for arrays
5522 // check if iterator pos fits to this JSON value
5523 if (pos.m_object != this)
5525 JSON_THROW(std::domain_error("iterator does not fit current value"));
5528 // insert to array and return iterator
5529 iterator result(this);
5530 result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
5534 JSON_THROW(std::domain_error("cannot use insert() with " + type_name()));
5538 @brief inserts element
5539 @copydoc insert(const_iterator, const basic_json&)
5541 iterator insert(const_iterator pos, basic_json&& val)
5543 return insert(pos, val);
5547 @brief inserts elements
5549 Inserts @a cnt copies of @a val before iterator @a pos.
5551 @param[in] pos iterator before which the content will be inserted; may be
5553 @param[in] cnt number of copies of @a val to insert
5554 @param[in] val element to insert
5555 @return iterator pointing to the first element inserted, or @a pos if
5558 @throw std::domain_error if called on JSON values other than arrays;
5559 example: `"cannot use insert() with string"`
5560 @throw std::domain_error if @a pos is not an iterator of *this; example:
5561 `"iterator does not fit current value"`
5563 @complexity Linear in @a cnt plus linear in the distance between @a pos
5564 and end of the container.
5566 @liveexample{The example shows how `insert()` is used.,insert__count}
5568 @since version 1.0.0
5570 iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
5572 // insert only works for arrays
5575 // check if iterator pos fits to this JSON value
5576 if (pos.m_object != this)
5578 JSON_THROW(std::domain_error("iterator does not fit current value"));
5581 // insert to array and return iterator
5582 iterator result(this);
5583 result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
5587 JSON_THROW(std::domain_error("cannot use insert() with " + type_name()));
5591 @brief inserts elements
5593 Inserts elements from range `[first, last)` before iterator @a pos.
5595 @param[in] pos iterator before which the content will be inserted; may be
5597 @param[in] first begin of the range of elements to insert
5598 @param[in] last end of the range of elements to insert
5600 @throw std::domain_error if called on JSON values other than arrays;
5601 example: `"cannot use insert() with string"`
5602 @throw std::domain_error if @a pos is not an iterator of *this; example:
5603 `"iterator does not fit current value"`
5604 @throw std::domain_error if @a first and @a last do not belong to the same
5605 JSON value; example: `"iterators do not fit"`
5606 @throw std::domain_error if @a first or @a last are iterators into
5607 container for which insert is called; example: `"passed iterators may not
5608 belong to container"`
5610 @return iterator pointing to the first element inserted, or @a pos if
5613 @complexity Linear in `std::distance(first, last)` plus linear in the
5614 distance between @a pos and end of the container.
5616 @liveexample{The example shows how `insert()` is used.,insert__range}
5618 @since version 1.0.0
5620 iterator insert(const_iterator pos, const_iterator first, const_iterator last)
5622 // insert only works for arrays
5625 JSON_THROW(std::domain_error("cannot use insert() with " + type_name()));
5628 // check if iterator pos fits to this JSON value
5629 if (pos.m_object != this)
5631 JSON_THROW(std::domain_error("iterator does not fit current value"));
5634 // check if range iterators belong to the same JSON object
5635 if (first.m_object != last.m_object)
5637 JSON_THROW(std::domain_error("iterators do not fit"));
5640 if (first.m_object == this or last.m_object == this)
5642 JSON_THROW(std::domain_error("passed iterators may not belong to container"));
5645 // insert to array and return iterator
5646 iterator result(this);
5647 result.m_it.array_iterator = m_value.array->insert(
5648 pos.m_it.array_iterator,
5649 first.m_it.array_iterator,
5650 last.m_it.array_iterator);
5655 @brief inserts elements
5657 Inserts elements from initializer list @a ilist before iterator @a pos.
5659 @param[in] pos iterator before which the content will be inserted; may be
5661 @param[in] ilist initializer list to insert the values from
5663 @throw std::domain_error if called on JSON values other than arrays;
5664 example: `"cannot use insert() with string"`
5665 @throw std::domain_error if @a pos is not an iterator of *this; example:
5666 `"iterator does not fit current value"`
5668 @return iterator pointing to the first element inserted, or @a pos if
5671 @complexity Linear in `ilist.size()` plus linear in the distance between
5672 @a pos and end of the container.
5674 @liveexample{The example shows how `insert()` is used.,insert__ilist}
5676 @since version 1.0.0
5678 iterator insert(const_iterator pos, std::initializer_list<basic_json> ilist)
5680 // insert only works for arrays
5683 JSON_THROW(std::domain_error("cannot use insert() with " + type_name()));
5686 // check if iterator pos fits to this JSON value
5687 if (pos.m_object != this)
5689 JSON_THROW(std::domain_error("iterator does not fit current value"));
5692 // insert to array and return iterator
5693 iterator result(this);
5694 result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist);
5699 @brief exchanges the values
5701 Exchanges the contents of the JSON value with those of @a other. Does not
5702 invoke any move, copy, or swap operations on individual elements. All
5703 iterators and references remain valid. The past-the-end iterator is
5706 @param[in,out] other JSON value to exchange the contents with
5708 @complexity Constant.
5710 @liveexample{The example below shows how JSON values can be swapped with
5711 `swap()`.,swap__reference}
5713 @since version 1.0.0
5715 void swap(reference other) noexcept (
5716 std::is_nothrow_move_constructible<value_t>::value and
5717 std::is_nothrow_move_assignable<value_t>::value and
5718 std::is_nothrow_move_constructible<json_value>::value and
5719 std::is_nothrow_move_assignable<json_value>::value
5722 std::swap(m_type, other.m_type);
5723 std::swap(m_value, other.m_value);
5728 @brief exchanges the values
5730 Exchanges the contents of a JSON array with those of @a other. Does not
5731 invoke any move, copy, or swap operations on individual elements. All
5732 iterators and references remain valid. The past-the-end iterator is
5735 @param[in,out] other array to exchange the contents with
5737 @throw std::domain_error when JSON value is not an array; example:
5738 `"cannot use swap() with string"`
5740 @complexity Constant.
5742 @liveexample{The example below shows how arrays can be swapped with
5743 `swap()`.,swap__array_t}
5745 @since version 1.0.0
5747 void swap(array_t& other)
5749 // swap only works for arrays
5752 std::swap(*(m_value.array), other);
5756 JSON_THROW(std::domain_error("cannot use swap() with " + type_name()));
5761 @brief exchanges the values
5763 Exchanges the contents of a JSON object with those of @a other. Does not
5764 invoke any move, copy, or swap operations on individual elements. All
5765 iterators and references remain valid. The past-the-end iterator is
5768 @param[in,out] other object to exchange the contents with
5770 @throw std::domain_error when JSON value is not an object; example:
5771 `"cannot use swap() with string"`
5773 @complexity Constant.
5775 @liveexample{The example below shows how objects can be swapped with
5776 `swap()`.,swap__object_t}
5778 @since version 1.0.0
5780 void swap(object_t& other)
5782 // swap only works for objects
5785 std::swap(*(m_value.object), other);
5789 JSON_THROW(std::domain_error("cannot use swap() with " + type_name()));
5794 @brief exchanges the values
5796 Exchanges the contents of a JSON string with those of @a other. Does not
5797 invoke any move, copy, or swap operations on individual elements. All
5798 iterators and references remain valid. The past-the-end iterator is
5801 @param[in,out] other string to exchange the contents with
5803 @throw std::domain_error when JSON value is not a string; example: `"cannot
5804 use swap() with boolean"`
5806 @complexity Constant.
5808 @liveexample{The example below shows how strings can be swapped with
5809 `swap()`.,swap__string_t}
5811 @since version 1.0.0
5813 void swap(string_t& other)
5815 // swap only works for strings
5818 std::swap(*(m_value.string), other);
5822 JSON_THROW(std::domain_error("cannot use swap() with " + type_name()));
5829 //////////////////////////////////////////
5830 // lexicographical comparison operators //
5831 //////////////////////////////////////////
5833 /// @name lexicographical comparison operators
5837 @brief comparison: equal
5839 Compares two JSON values for equality according to the following rules:
5840 - Two JSON values are equal if (1) they are from the same type and (2)
5841 their stored values are the same.
5842 - Integer and floating-point numbers are automatically converted before
5843 comparison. Floating-point numbers are compared indirectly: two
5844 floating-point numbers `f1` and `f2` are considered equal if neither
5845 `f1 > f2` nor `f2 > f1` holds.
5846 - Two JSON null values are equal.
5848 @param[in] lhs first JSON value to consider
5849 @param[in] rhs second JSON value to consider
5850 @return whether the values @a lhs and @a rhs are equal
5854 @liveexample{The example demonstrates comparing several JSON
5855 types.,operator__equal}
5857 @since version 1.0.0
5859 friend bool operator==(const_reference lhs, const_reference rhs) noexcept
5861 const auto lhs_type = lhs.type();
5862 const auto rhs_type = rhs.type();
5864 if (lhs_type == rhs_type)
5868 case value_t::array:
5870 return *lhs.m_value.array == *rhs.m_value.array;
5872 case value_t::object:
5874 return *lhs.m_value.object == *rhs.m_value.object;
5880 case value_t::string:
5882 return *lhs.m_value.string == *rhs.m_value.string;
5884 case value_t::boolean:
5886 return lhs.m_value.boolean == rhs.m_value.boolean;
5888 case value_t::number_integer:
5890 return lhs.m_value.number_integer == rhs.m_value.number_integer;
5892 case value_t::number_unsigned:
5894 return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
5896 case value_t::number_float:
5898 return lhs.m_value.number_float == rhs.m_value.number_float;
5906 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
5908 return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
5910 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
5912 return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
5914 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
5916 return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
5918 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
5920 return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
5922 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
5924 return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
5926 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
5928 return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
5935 @brief comparison: equal
5936 @copydoc operator==(const_reference, const_reference)
5938 template<typename ScalarType, typename std::enable_if<
5939 std::is_scalar<ScalarType>::value, int>::type = 0>
5940 friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
5942 return (lhs == basic_json(rhs));
5946 @brief comparison: equal
5947 @copydoc operator==(const_reference, const_reference)
5949 template<typename ScalarType, typename std::enable_if<
5950 std::is_scalar<ScalarType>::value, int>::type = 0>
5951 friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
5953 return (basic_json(lhs) == rhs);
5957 @brief comparison: not equal
5959 Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
5961 @param[in] lhs first JSON value to consider
5962 @param[in] rhs second JSON value to consider
5963 @return whether the values @a lhs and @a rhs are not equal
5967 @liveexample{The example demonstrates comparing several JSON
5968 types.,operator__notequal}
5970 @since version 1.0.0
5972 friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
5974 return not (lhs == rhs);
5978 @brief comparison: not equal
5979 @copydoc operator!=(const_reference, const_reference)
5981 template<typename ScalarType, typename std::enable_if<
5982 std::is_scalar<ScalarType>::value, int>::type = 0>
5983 friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
5985 return (lhs != basic_json(rhs));
5989 @brief comparison: not equal
5990 @copydoc operator!=(const_reference, const_reference)
5992 template<typename ScalarType, typename std::enable_if<
5993 std::is_scalar<ScalarType>::value, int>::type = 0>
5994 friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
5996 return (basic_json(lhs) != rhs);
6000 @brief comparison: less than
6002 Compares whether one JSON value @a lhs is less than another JSON value @a
6003 rhs according to the following rules:
6004 - If @a lhs and @a rhs have the same type, the values are compared using
6005 the default `<` operator.
6006 - Integer and floating-point numbers are automatically converted before
6008 - In case @a lhs and @a rhs have different types, the values are ignored
6009 and the order of the types is considered, see
6010 @ref operator<(const value_t, const value_t).
6012 @param[in] lhs first JSON value to consider
6013 @param[in] rhs second JSON value to consider
6014 @return whether @a lhs is less than @a rhs
6018 @liveexample{The example demonstrates comparing several JSON
6019 types.,operator__less}
6021 @since version 1.0.0
6023 friend bool operator<(const_reference lhs, const_reference rhs) noexcept
6025 const auto lhs_type = lhs.type();
6026 const auto rhs_type = rhs.type();
6028 if (lhs_type == rhs_type)
6032 case value_t::array:
6034 return *lhs.m_value.array < *rhs.m_value.array;
6036 case value_t::object:
6038 return *lhs.m_value.object < *rhs.m_value.object;
6044 case value_t::string:
6046 return *lhs.m_value.string < *rhs.m_value.string;
6048 case value_t::boolean:
6050 return lhs.m_value.boolean < rhs.m_value.boolean;
6052 case value_t::number_integer:
6054 return lhs.m_value.number_integer < rhs.m_value.number_integer;
6056 case value_t::number_unsigned:
6058 return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned;
6060 case value_t::number_float:
6062 return lhs.m_value.number_float < rhs.m_value.number_float;
6070 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
6072 return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
6074 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
6076 return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
6078 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
6080 return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
6082 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
6084 return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
6086 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
6088 return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
6090 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
6092 return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
6095 // We only reach this line if we cannot compare values. In that case,
6096 // we compare types. Note we have to call the operator explicitly,
6097 // because MSVC has problems otherwise.
6098 return operator<(lhs_type, rhs_type);
6102 @brief comparison: less than or equal
6104 Compares whether one JSON value @a lhs is less than or equal to another
6105 JSON value by calculating `not (rhs < lhs)`.
6107 @param[in] lhs first JSON value to consider
6108 @param[in] rhs second JSON value to consider
6109 @return whether @a lhs is less than or equal to @a rhs
6113 @liveexample{The example demonstrates comparing several JSON
6114 types.,operator__greater}
6116 @since version 1.0.0
6118 friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
6120 return not (rhs < lhs);
6124 @brief comparison: greater than
6126 Compares whether one JSON value @a lhs is greater than another
6127 JSON value by calculating `not (lhs <= rhs)`.
6129 @param[in] lhs first JSON value to consider
6130 @param[in] rhs second JSON value to consider
6131 @return whether @a lhs is greater than to @a rhs
6135 @liveexample{The example demonstrates comparing several JSON
6136 types.,operator__lessequal}
6138 @since version 1.0.0
6140 friend bool operator>(const_reference lhs, const_reference rhs) noexcept
6142 return not (lhs <= rhs);
6146 @brief comparison: greater than or equal
6148 Compares whether one JSON value @a lhs is greater than or equal to another
6149 JSON value by calculating `not (lhs < rhs)`.
6151 @param[in] lhs first JSON value to consider
6152 @param[in] rhs second JSON value to consider
6153 @return whether @a lhs is greater than or equal to @a rhs
6157 @liveexample{The example demonstrates comparing several JSON
6158 types.,operator__greaterequal}
6160 @since version 1.0.0
6162 friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
6164 return not (lhs < rhs);
6174 /// @name serialization
6178 @brief serialize to stream
6180 Serialize the given JSON value @a j to the output stream @a o. The JSON
6181 value will be serialized using the @ref dump member function. The
6182 indentation of the output can be controlled with the member variable
6183 `width` of the output stream @a o. For instance, using the manipulator
6184 `std::setw(4)` on @a o sets the indentation level to `4` and the
6185 serialization result is the same as calling `dump(4)`.
6187 @param[in,out] o stream to serialize to
6188 @param[in] j JSON value to serialize
6190 @return the stream @a o
6194 @liveexample{The example below shows the serialization with different
6195 parameters to `width` to adjust the indentation level.,operator_serialize}
6197 @since version 1.0.0
6199 friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
6201 // read width member and use it as indentation parameter if nonzero
6202 const bool pretty_print = (o.width() > 0);
6203 const auto indentation = (pretty_print ? o.width() : 0);
6205 // reset width to 0 for subsequent calls to this stream
6208 // do the actual serialization
6209 j.dump(o, pretty_print, static_cast<unsigned int>(indentation));
6215 @brief serialize to stream
6216 @copydoc operator<<(std::ostream&, const basic_json&)
6218 friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
6226 /////////////////////
6227 // deserialization //
6228 /////////////////////
6230 /// @name deserialization
6234 @brief deserialize from an array
6236 This function reads from an array of 1-byte values.
6238 @pre Each element of the container has a size of 1 byte. Violating this
6239 precondition yields undefined behavior. **This precondition is enforced
6240 with a static assertion.**
6242 @param[in] array array to read from
6243 @param[in] cb a parser callback function of type @ref parser_callback_t
6244 which is used to control the deserialization by filtering unwanted values
6247 @return result of the deserialization
6249 @complexity Linear in the length of the input. The parser is a predictive
6250 LL(1) parser. The complexity can be higher if the parser callback function
6251 @a cb has a super-linear complexity.
6253 @note A UTF-8 byte order mark is silently ignored.
6255 @liveexample{The example below demonstrates the `parse()` function reading
6256 from an array.,parse__array__parser_callback_t}
6258 @since version 2.0.3
6260 template<class T, std::size_t N>
6261 static basic_json parse(T (&array)[N],
6262 const parser_callback_t cb = nullptr)
6264 // delegate the call to the iterator-range parse overload
6265 return parse(std::begin(array), std::end(array), cb);
6269 @brief deserialize from string literal
6271 @tparam CharT character/literal type with size of 1 byte
6272 @param[in] s string literal to read a serialized JSON value from
6273 @param[in] cb a parser callback function of type @ref parser_callback_t
6274 which is used to control the deserialization by filtering unwanted values
6277 @return result of the deserialization
6279 @complexity Linear in the length of the input. The parser is a predictive
6280 LL(1) parser. The complexity can be higher if the parser callback function
6281 @a cb has a super-linear complexity.
6283 @note A UTF-8 byte order mark is silently ignored.
6284 @note String containers like `std::string` or @ref string_t can be parsed
6285 with @ref parse(const ContiguousContainer&, const parser_callback_t)
6287 @liveexample{The example below demonstrates the `parse()` function with
6288 and without callback function.,parse__string__parser_callback_t}
6290 @sa @ref parse(std::istream&, const parser_callback_t) for a version that
6291 reads from an input stream
6293 @since version 1.0.0 (originally for @ref string_t)
6295 template<typename CharT, typename std::enable_if<
6296 std::is_pointer<CharT>::value and
6297 std::is_integral<typename std::remove_pointer<CharT>::type>::value and
6298 sizeof(typename std::remove_pointer<CharT>::type) == 1, int>::type = 0>
6299 static basic_json parse(const CharT s,
6300 const parser_callback_t cb = nullptr)
6302 return parser(reinterpret_cast<const char*>(s), cb).parse();
6306 @brief deserialize from stream
6308 @param[in,out] i stream to read a serialized JSON value from
6309 @param[in] cb a parser callback function of type @ref parser_callback_t
6310 which is used to control the deserialization by filtering unwanted values
6313 @return result of the deserialization
6315 @complexity Linear in the length of the input. The parser is a predictive
6316 LL(1) parser. The complexity can be higher if the parser callback function
6317 @a cb has a super-linear complexity.
6319 @note A UTF-8 byte order mark is silently ignored.
6321 @liveexample{The example below demonstrates the `parse()` function with
6322 and without callback function.,parse__istream__parser_callback_t}
6324 @sa @ref parse(const CharT, const parser_callback_t) for a version
6325 that reads from a string
6327 @since version 1.0.0
6329 static basic_json parse(std::istream& i,
6330 const parser_callback_t cb = nullptr)
6332 return parser(i, cb).parse();
6336 @copydoc parse(std::istream&, const parser_callback_t)
6338 static basic_json parse(std::istream&& i,
6339 const parser_callback_t cb = nullptr)
6341 return parser(i, cb).parse();
6345 @brief deserialize from an iterator range with contiguous storage
6347 This function reads from an iterator range of a container with contiguous
6348 storage of 1-byte values. Compatible container types include
6349 `std::vector`, `std::string`, `std::array`, `std::valarray`, and
6350 `std::initializer_list`. Furthermore, C-style arrays can be used with
6351 `std::begin()`/`std::end()`. User-defined containers can be used as long
6352 as they implement random-access iterators and a contiguous storage.
6354 @pre The iterator range is contiguous. Violating this precondition yields
6355 undefined behavior. **This precondition is enforced with an assertion.**
6356 @pre Each element in the range has a size of 1 byte. Violating this
6357 precondition yields undefined behavior. **This precondition is enforced
6358 with a static assertion.**
6360 @warning There is no way to enforce all preconditions at compile-time. If
6361 the function is called with noncompliant iterators and with
6362 assertions switched off, the behavior is undefined and will most
6363 likely yield segmentation violation.
6365 @tparam IteratorType iterator of container with contiguous storage
6366 @param[in] first begin of the range to parse (included)
6367 @param[in] last end of the range to parse (excluded)
6368 @param[in] cb a parser callback function of type @ref parser_callback_t
6369 which is used to control the deserialization by filtering unwanted values
6372 @return result of the deserialization
6374 @complexity Linear in the length of the input. The parser is a predictive
6375 LL(1) parser. The complexity can be higher if the parser callback function
6376 @a cb has a super-linear complexity.
6378 @note A UTF-8 byte order mark is silently ignored.
6380 @liveexample{The example below demonstrates the `parse()` function reading
6381 from an iterator range.,parse__iteratortype__parser_callback_t}
6383 @since version 2.0.3
6385 template<class IteratorType, typename std::enable_if<
6387 std::random_access_iterator_tag,
6388 typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
6389 static basic_json parse(IteratorType first, IteratorType last,
6390 const parser_callback_t cb = nullptr)
6392 // assertion to check that the iterator range is indeed contiguous,
6393 // see http://stackoverflow.com/a/35008842/266378 for more discussion
6394 assert(std::accumulate(first, last, std::pair<bool, int>(true, 0),
6395 [&first](std::pair<bool, int> res, decltype(*first) val)
6397 res.first &= (val == *(std::next(std::addressof(*first), res.second++)));
6401 // assertion to check that each element is 1 byte long
6402 static_assert(sizeof(typename std::iterator_traits<IteratorType>::value_type) == 1,
6403 "each element in the iterator range must have the size of 1 byte");
6405 // if iterator range is empty, create a parser with an empty string
6406 // to generate "unexpected EOF" error message
6407 if (std::distance(first, last) <= 0)
6409 return parser("").parse();
6412 return parser(first, last, cb).parse();
6416 @brief deserialize from a container with contiguous storage
6418 This function reads from a container with contiguous storage of 1-byte
6419 values. Compatible container types include `std::vector`, `std::string`,
6420 `std::array`, and `std::initializer_list`. User-defined containers can be
6421 used as long as they implement random-access iterators and a contiguous
6424 @pre The container storage is contiguous. Violating this precondition
6425 yields undefined behavior. **This precondition is enforced with an
6427 @pre Each element of the container has a size of 1 byte. Violating this
6428 precondition yields undefined behavior. **This precondition is enforced
6429 with a static assertion.**
6431 @warning There is no way to enforce all preconditions at compile-time. If
6432 the function is called with a noncompliant container and with
6433 assertions switched off, the behavior is undefined and will most
6434 likely yield segmentation violation.
6436 @tparam ContiguousContainer container type with contiguous storage
6437 @param[in] c container to read from
6438 @param[in] cb a parser callback function of type @ref parser_callback_t
6439 which is used to control the deserialization by filtering unwanted values
6442 @return result of the deserialization
6444 @complexity Linear in the length of the input. The parser is a predictive
6445 LL(1) parser. The complexity can be higher if the parser callback function
6446 @a cb has a super-linear complexity.
6448 @note A UTF-8 byte order mark is silently ignored.
6450 @liveexample{The example below demonstrates the `parse()` function reading
6451 from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
6453 @since version 2.0.3
6455 template<class ContiguousContainer, typename std::enable_if<
6456 not std::is_pointer<ContiguousContainer>::value and
6458 std::random_access_iterator_tag,
6459 typename std::iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value
6461 static basic_json parse(const ContiguousContainer& c,
6462 const parser_callback_t cb = nullptr)
6464 // delegate the call to the iterator-range parse overload
6465 return parse(std::begin(c), std::end(c), cb);
6469 @brief deserialize from stream
6471 Deserializes an input stream to a JSON value.
6473 @param[in,out] i input stream to read a serialized JSON value from
6474 @param[in,out] j JSON value to write the deserialized input to
6476 @throw std::invalid_argument in case of parse errors
6478 @complexity Linear in the length of the input. The parser is a predictive
6481 @note A UTF-8 byte order mark is silently ignored.
6483 @liveexample{The example below shows how a JSON value is constructed by
6484 reading a serialization from a stream.,operator_deserialize}
6486 @sa parse(std::istream&, const parser_callback_t) for a variant with a
6487 parser callback function to filter values while parsing
6489 @since version 1.0.0
6491 friend std::istream& operator<<(basic_json& j, std::istream& i)
6493 j = parser(i).parse();
6498 @brief deserialize from stream
6499 @copydoc operator<<(basic_json&, std::istream&)
6501 friend std::istream& operator>>(std::istream& i, basic_json& j)
6503 j = parser(i).parse();
6509 //////////////////////////////////////////
6510 // binary serialization/deserialization //
6511 //////////////////////////////////////////
6513 /// @name binary serialization/deserialization support
6518 @note Some code in the switch cases has been copied, because otherwise
6519 copilers would complain about implicit fallthrough and there is no
6520 portable attribute to mute such warnings.
6522 template<typename T>
6523 static void add_to_vector(std::vector<uint8_t>& vec, size_t bytes, const T number)
6525 assert(bytes == 1 or bytes == 2 or bytes == 4 or bytes == 8);
6531 vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 070) & 0xff));
6532 vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 060) & 0xff));
6533 vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 050) & 0xff));
6534 vec.push_back(static_cast<uint8_t>((static_cast<uint64_t>(number) >> 040) & 0xff));
6535 vec.push_back(static_cast<uint8_t>((number >> 030) & 0xff));
6536 vec.push_back(static_cast<uint8_t>((number >> 020) & 0xff));
6537 vec.push_back(static_cast<uint8_t>((number >> 010) & 0xff));
6538 vec.push_back(static_cast<uint8_t>(number & 0xff));
6544 vec.push_back(static_cast<uint8_t>((number >> 030) & 0xff));
6545 vec.push_back(static_cast<uint8_t>((number >> 020) & 0xff));
6546 vec.push_back(static_cast<uint8_t>((number >> 010) & 0xff));
6547 vec.push_back(static_cast<uint8_t>(number & 0xff));
6553 vec.push_back(static_cast<uint8_t>((number >> 010) & 0xff));
6554 vec.push_back(static_cast<uint8_t>(number & 0xff));
6560 vec.push_back(static_cast<uint8_t>(number & 0xff));
6567 @brief take sufficient bytes from a vector to fill an integer variable
6569 In the context of binary serialization formats, we need to read several
6570 bytes from a byte vector and combine them to multi-byte integral data
6573 @param[in] vec byte vector to read from
6574 @param[in] current_index the position in the vector after which to read
6576 @return the next sizeof(T) bytes from @a vec, in reverse order as T
6578 @tparam T the integral return type
6580 @throw std::out_of_range if there are less than sizeof(T)+1 bytes in the
6581 vector @a vec to read
6583 In the for loop, the bytes from the vector are copied in reverse order into
6584 the return value. In the figures below, let sizeof(T)=4 and `i` be the loop
6589 vec: | | | a | b | c | d | T: | | | | |
6591 current_index i ptr sizeof(T)
6595 vec: | | | a | b | c | d | T: | d | c | b | a |
6600 @sa Code adapted from <http://stackoverflow.com/a/41031865/266378>.
6602 template<typename T>
6603 static T get_from_vector(const std::vector<uint8_t>& vec, const size_t current_index)
6605 if (current_index + sizeof(T) + 1 > vec.size())
6607 JSON_THROW(std::out_of_range("cannot read " + std::to_string(sizeof(T)) + " bytes from vector"));
6611 auto* ptr = reinterpret_cast<uint8_t*>(&result);
6612 for (size_t i = 0; i < sizeof(T); ++i)
6614 *ptr++ = vec[current_index + sizeof(T) - i];
6620 @brief create a MessagePack serialization of a given JSON value
6622 This is a straightforward implementation of the MessagePack specification.
6624 @param[in] j JSON value to serialize
6625 @param[in,out] v byte vector to write the serialization to
6627 @sa https://github.com/msgpack/msgpack/blob/master/spec.md
6629 static void to_msgpack_internal(const basic_json& j, std::vector<uint8_t>& v)
6640 case value_t::boolean:
6643 v.push_back(j.m_value.boolean ? 0xc3 : 0xc2);
6647 case value_t::number_integer:
6649 if (j.m_value.number_integer >= 0)
6651 // MessagePack does not differentiate between positive
6652 // signed integers and unsigned integers. Therefore, we
6653 // used the code from the value_t::number_unsigned case
6655 if (j.m_value.number_unsigned < 128)
6658 add_to_vector(v, 1, j.m_value.number_unsigned);
6660 else if (j.m_value.number_unsigned <= std::numeric_limits<uint8_t>::max())
6664 add_to_vector(v, 1, j.m_value.number_unsigned);
6666 else if (j.m_value.number_unsigned <= std::numeric_limits<uint16_t>::max())
6670 add_to_vector(v, 2, j.m_value.number_unsigned);
6672 else if (j.m_value.number_unsigned <= std::numeric_limits<uint32_t>::max())
6676 add_to_vector(v, 4, j.m_value.number_unsigned);
6678 else if (j.m_value.number_unsigned <= std::numeric_limits<uint64_t>::max())
6682 add_to_vector(v, 8, j.m_value.number_unsigned);
6687 if (j.m_value.number_integer >= -32)
6690 add_to_vector(v, 1, j.m_value.number_integer);
6692 else if (j.m_value.number_integer >= std::numeric_limits<int8_t>::min() and j.m_value.number_integer <= std::numeric_limits<int8_t>::max())
6696 add_to_vector(v, 1, j.m_value.number_integer);
6698 else if (j.m_value.number_integer >= std::numeric_limits<int16_t>::min() and j.m_value.number_integer <= std::numeric_limits<int16_t>::max())
6702 add_to_vector(v, 2, j.m_value.number_integer);
6704 else if (j.m_value.number_integer >= std::numeric_limits<int32_t>::min() and j.m_value.number_integer <= std::numeric_limits<int32_t>::max())
6708 add_to_vector(v, 4, j.m_value.number_integer);
6710 else if (j.m_value.number_integer >= std::numeric_limits<int64_t>::min() and j.m_value.number_integer <= std::numeric_limits<int64_t>::max())
6714 add_to_vector(v, 8, j.m_value.number_integer);
6720 case value_t::number_unsigned:
6722 if (j.m_value.number_unsigned < 128)
6725 add_to_vector(v, 1, j.m_value.number_unsigned);
6727 else if (j.m_value.number_unsigned <= std::numeric_limits<uint8_t>::max())
6731 add_to_vector(v, 1, j.m_value.number_unsigned);
6733 else if (j.m_value.number_unsigned <= std::numeric_limits<uint16_t>::max())
6737 add_to_vector(v, 2, j.m_value.number_unsigned);
6739 else if (j.m_value.number_unsigned <= std::numeric_limits<uint32_t>::max())
6743 add_to_vector(v, 4, j.m_value.number_unsigned);
6745 else if (j.m_value.number_unsigned <= std::numeric_limits<uint64_t>::max())
6749 add_to_vector(v, 8, j.m_value.number_unsigned);
6754 case value_t::number_float:
6758 const auto* helper = reinterpret_cast<const uint8_t*>(&(j.m_value.number_float));
6759 for (size_t i = 0; i < 8; ++i)
6761 v.push_back(helper[7 - i]);
6766 case value_t::string:
6768 const auto N = j.m_value.string->size();
6772 v.push_back(static_cast<uint8_t>(0xa0 | N));
6778 add_to_vector(v, 1, N);
6780 else if (N <= 65535)
6784 add_to_vector(v, 2, N);
6786 else if (N <= 4294967295)
6790 add_to_vector(v, 4, N);
6794 std::copy(j.m_value.string->begin(), j.m_value.string->end(),
6795 std::back_inserter(v));
6799 case value_t::array:
6801 const auto N = j.m_value.array->size();
6805 v.push_back(static_cast<uint8_t>(0x90 | N));
6807 else if (N <= 0xffff)
6811 add_to_vector(v, 2, N);
6813 else if (N <= 0xffffffff)
6817 add_to_vector(v, 4, N);
6820 // append each element
6821 for (const auto& el : *j.m_value.array)
6823 to_msgpack_internal(el, v);
6828 case value_t::object:
6830 const auto N = j.m_value.object->size();
6834 v.push_back(static_cast<uint8_t>(0x80 | (N & 0xf)));
6836 else if (N <= 65535)
6840 add_to_vector(v, 2, N);
6842 else if (N <= 4294967295)
6846 add_to_vector(v, 4, N);
6849 // append each element
6850 for (const auto& el : *j.m_value.object)
6852 to_msgpack_internal(el.first, v);
6853 to_msgpack_internal(el.second, v);
6866 @brief create a CBOR serialization of a given JSON value
6868 This is a straightforward implementation of the CBOR specification.
6870 @param[in] j JSON value to serialize
6871 @param[in,out] v byte vector to write the serialization to
6873 @sa https://tools.ietf.org/html/rfc7049
6875 static void to_cbor_internal(const basic_json& j, std::vector<uint8_t>& v)
6885 case value_t::boolean:
6887 v.push_back(j.m_value.boolean ? 0xf5 : 0xf4);
6891 case value_t::number_integer:
6893 if (j.m_value.number_integer >= 0)
6895 // CBOR does not differentiate between positive signed
6896 // integers and unsigned integers. Therefore, we used the
6897 // code from the value_t::number_unsigned case here.
6898 if (j.m_value.number_integer <= 0x17)
6900 add_to_vector(v, 1, j.m_value.number_integer);
6902 else if (j.m_value.number_integer <= std::numeric_limits<uint8_t>::max())
6906 add_to_vector(v, 1, j.m_value.number_integer);
6908 else if (j.m_value.number_integer <= std::numeric_limits<uint16_t>::max())
6911 // two-byte uint16_t
6912 add_to_vector(v, 2, j.m_value.number_integer);
6914 else if (j.m_value.number_integer <= std::numeric_limits<uint32_t>::max())
6917 // four-byte uint32_t
6918 add_to_vector(v, 4, j.m_value.number_integer);
6923 // eight-byte uint64_t
6924 add_to_vector(v, 8, j.m_value.number_integer);
6929 // The conversions below encode the sign in the first
6930 // byte, and the value is converted to a positive number.
6931 const auto positive_number = -1 - j.m_value.number_integer;
6932 if (j.m_value.number_integer >= -24)
6934 v.push_back(static_cast<uint8_t>(0x20 + positive_number));
6936 else if (positive_number <= std::numeric_limits<uint8_t>::max())
6940 add_to_vector(v, 1, positive_number);
6942 else if (positive_number <= std::numeric_limits<uint16_t>::max())
6946 add_to_vector(v, 2, positive_number);
6948 else if (positive_number <= std::numeric_limits<uint32_t>::max())
6952 add_to_vector(v, 4, positive_number);
6958 add_to_vector(v, 8, positive_number);
6964 case value_t::number_unsigned:
6966 if (j.m_value.number_unsigned <= 0x17)
6968 v.push_back(static_cast<uint8_t>(j.m_value.number_unsigned));
6970 else if (j.m_value.number_unsigned <= 0xff)
6974 add_to_vector(v, 1, j.m_value.number_unsigned);
6976 else if (j.m_value.number_unsigned <= 0xffff)
6979 // two-byte uint16_t
6980 add_to_vector(v, 2, j.m_value.number_unsigned);
6982 else if (j.m_value.number_unsigned <= 0xffffffff)
6985 // four-byte uint32_t
6986 add_to_vector(v, 4, j.m_value.number_unsigned);
6988 else if (j.m_value.number_unsigned <= 0xffffffffffffffff)
6991 // eight-byte uint64_t
6992 add_to_vector(v, 8, j.m_value.number_unsigned);
6997 case value_t::number_float:
6999 // Double-Precision Float
7001 const auto* helper = reinterpret_cast<const uint8_t*>(&(j.m_value.number_float));
7002 for (size_t i = 0; i < 8; ++i)
7004 v.push_back(helper[7 - i]);
7009 case value_t::string:
7011 const auto N = j.m_value.string->size();
7014 v.push_back(0x60 + static_cast<uint8_t>(N)); // 1 byte for string + size
7018 v.push_back(0x78); // one-byte uint8_t for N
7019 add_to_vector(v, 1, N);
7021 else if (N <= 0xffff)
7023 v.push_back(0x79); // two-byte uint16_t for N
7024 add_to_vector(v, 2, N);
7026 else if (N <= 0xffffffff)
7028 v.push_back(0x7a); // four-byte uint32_t for N
7029 add_to_vector(v, 4, N);
7032 else if (N <= 0xffffffffffffffff)
7034 v.push_back(0x7b); // eight-byte uint64_t for N
7035 add_to_vector(v, 8, N);
7040 std::copy(j.m_value.string->begin(), j.m_value.string->end(),
7041 std::back_inserter(v));
7045 case value_t::array:
7047 const auto N = j.m_value.array->size();
7050 v.push_back(0x80 + static_cast<uint8_t>(N)); // 1 byte for array + size
7054 v.push_back(0x98); // one-byte uint8_t for N
7055 add_to_vector(v, 1, N);
7057 else if (N <= 0xffff)
7059 v.push_back(0x99); // two-byte uint16_t for N
7060 add_to_vector(v, 2, N);
7062 else if (N <= 0xffffffff)
7064 v.push_back(0x9a); // four-byte uint32_t for N
7065 add_to_vector(v, 4, N);
7068 else if (N <= 0xffffffffffffffff)
7070 v.push_back(0x9b); // eight-byte uint64_t for N
7071 add_to_vector(v, 8, N);
7075 // append each element
7076 for (const auto& el : *j.m_value.array)
7078 to_cbor_internal(el, v);
7083 case value_t::object:
7085 const auto N = j.m_value.object->size();
7088 v.push_back(0xa0 + static_cast<uint8_t>(N)); // 1 byte for object + size
7093 add_to_vector(v, 1, N); // one-byte uint8_t for N
7095 else if (N <= 0xffff)
7098 add_to_vector(v, 2, N); // two-byte uint16_t for N
7100 else if (N <= 0xffffffff)
7103 add_to_vector(v, 4, N); // four-byte uint32_t for N
7106 else if (N <= 0xffffffffffffffff)
7109 add_to_vector(v, 8, N); // eight-byte uint64_t for N
7113 // append each element
7114 for (const auto& el : *j.m_value.object)
7116 to_cbor_internal(el.first, v);
7117 to_cbor_internal(el.second, v);
7131 @brief checks if given lengths do not exceed the size of a given vector
7133 To secure the access to the byte vector during CBOR/MessagePack
7134 deserialization, bytes are copied from the vector into buffers. This
7135 function checks if the number of bytes to copy (@a len) does not exceed
7136 the size @s size of the vector. Additionally, an @a offset is given from
7137 where to start reading the bytes.
7139 This function checks whether reading the bytes is safe; that is, offset is
7140 a valid index in the vector, offset+len
7142 @param[in] size size of the byte vector
7143 @param[in] len number of bytes to read
7144 @param[in] offset offset where to start reading
7146 vec: x x x x x X X X X X
7150 @throws out_of_range if `len > v.size()`
7152 static void check_length(const size_t size, const size_t len, const size_t offset)
7154 // simple case: requested length is greater than the vector's length
7155 if (len > size or offset > size)
7157 JSON_THROW(std::out_of_range("len out of range"));
7160 // second case: adding offset would result in overflow
7161 if ((size > (std::numeric_limits<size_t>::max() - offset)))
7163 JSON_THROW(std::out_of_range("len+offset out of range"));
7166 // last case: reading past the end of the vector
7167 if (len + offset > size)
7169 JSON_THROW(std::out_of_range("len+offset out of range"));
7174 @brief create a JSON value from a given MessagePack vector
7176 @param[in] v MessagePack serialization
7177 @param[in] idx byte index to start reading from @a v
7179 @return deserialized JSON value
7181 @throw std::invalid_argument if unsupported features from MessagePack were
7182 used in the given vector @a v or if the input is not valid MessagePack
7183 @throw std::out_of_range if the given vector ends prematurely
7185 @sa https://github.com/msgpack/msgpack/blob/master/spec.md
7187 static basic_json from_msgpack_internal(const std::vector<uint8_t>& v, size_t& idx)
7189 // make sure reading 1 byte is safe
7190 check_length(v.size(), 1, idx);
7192 // store and increment index
7193 const size_t current_idx = idx++;
7195 if (v[current_idx] <= 0xbf)
7197 if (v[current_idx] <= 0x7f) // positive fixint
7199 return v[current_idx];
7201 if (v[current_idx] <= 0x8f) // fixmap
7203 basic_json result = value_t::object;
7204 const size_t len = v[current_idx] & 0x0f;
7205 for (size_t i = 0; i < len; ++i)
7207 std::string key = from_msgpack_internal(v, idx);
7208 result[key] = from_msgpack_internal(v, idx);
7212 else if (v[current_idx] <= 0x9f) // fixarray
7214 basic_json result = value_t::array;
7215 const size_t len = v[current_idx] & 0x0f;
7216 for (size_t i = 0; i < len; ++i)
7218 result.push_back(from_msgpack_internal(v, idx));
7224 const size_t len = v[current_idx] & 0x1f;
7225 const size_t offset = current_idx + 1;
7226 idx += len; // skip content bytes
7227 check_length(v.size(), len, offset);
7228 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
7231 else if (v[current_idx] >= 0xe0) // negative fixint
7233 return static_cast<int8_t>(v[current_idx]);
7237 switch (v[current_idx])
7241 return value_t::null;
7254 case 0xca: // float 32
7256 // copy bytes in reverse order into the double variable
7258 for (size_t byte = 0; byte < sizeof(float); ++byte)
7260 reinterpret_cast<uint8_t*>(&res)[sizeof(float) - byte - 1] = v.at(current_idx + 1 + byte);
7262 idx += sizeof(float); // skip content bytes
7266 case 0xcb: // float 64
7268 // copy bytes in reverse order into the double variable
7270 for (size_t byte = 0; byte < sizeof(double); ++byte)
7272 reinterpret_cast<uint8_t*>(&res)[sizeof(double) - byte - 1] = v.at(current_idx + 1 + byte);
7274 idx += sizeof(double); // skip content bytes
7278 case 0xcc: // uint 8
7280 idx += 1; // skip content byte
7281 return get_from_vector<uint8_t>(v, current_idx);
7284 case 0xcd: // uint 16
7286 idx += 2; // skip 2 content bytes
7287 return get_from_vector<uint16_t>(v, current_idx);
7290 case 0xce: // uint 32
7292 idx += 4; // skip 4 content bytes
7293 return get_from_vector<uint32_t>(v, current_idx);
7296 case 0xcf: // uint 64
7298 idx += 8; // skip 8 content bytes
7299 return get_from_vector<uint64_t>(v, current_idx);
7304 idx += 1; // skip content byte
7305 return get_from_vector<int8_t>(v, current_idx);
7308 case 0xd1: // int 16
7310 idx += 2; // skip 2 content bytes
7311 return get_from_vector<int16_t>(v, current_idx);
7314 case 0xd2: // int 32
7316 idx += 4; // skip 4 content bytes
7317 return get_from_vector<int32_t>(v, current_idx);
7320 case 0xd3: // int 64
7322 idx += 8; // skip 8 content bytes
7323 return get_from_vector<int64_t>(v, current_idx);
7328 const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx));
7329 const size_t offset = current_idx + 2;
7330 idx += len + 1; // skip size byte + content bytes
7331 check_length(v.size(), len, offset);
7332 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
7335 case 0xda: // str 16
7337 const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
7338 const size_t offset = current_idx + 3;
7339 idx += len + 2; // skip 2 size bytes + content bytes
7340 check_length(v.size(), len, offset);
7341 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
7344 case 0xdb: // str 32
7346 const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
7347 const size_t offset = current_idx + 5;
7348 idx += len + 4; // skip 4 size bytes + content bytes
7349 check_length(v.size(), len, offset);
7350 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
7353 case 0xdc: // array 16
7355 basic_json result = value_t::array;
7356 const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
7357 idx += 2; // skip 2 size bytes
7358 for (size_t i = 0; i < len; ++i)
7360 result.push_back(from_msgpack_internal(v, idx));
7365 case 0xdd: // array 32
7367 basic_json result = value_t::array;
7368 const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
7369 idx += 4; // skip 4 size bytes
7370 for (size_t i = 0; i < len; ++i)
7372 result.push_back(from_msgpack_internal(v, idx));
7377 case 0xde: // map 16
7379 basic_json result = value_t::object;
7380 const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
7381 idx += 2; // skip 2 size bytes
7382 for (size_t i = 0; i < len; ++i)
7384 std::string key = from_msgpack_internal(v, idx);
7385 result[key] = from_msgpack_internal(v, idx);
7390 case 0xdf: // map 32
7392 basic_json result = value_t::object;
7393 const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
7394 idx += 4; // skip 4 size bytes
7395 for (size_t i = 0; i < len; ++i)
7397 std::string key = from_msgpack_internal(v, idx);
7398 result[key] = from_msgpack_internal(v, idx);
7405 JSON_THROW(std::invalid_argument("error parsing a msgpack @ " + std::to_string(current_idx) + ": " + std::to_string(static_cast<int>(v[current_idx]))));
7412 @brief create a JSON value from a given CBOR vector
7414 @param[in] v CBOR serialization
7415 @param[in] idx byte index to start reading from @a v
7417 @return deserialized JSON value
7419 @throw std::invalid_argument if unsupported features from CBOR were used in
7420 the given vector @a v or if the input is not valid CBOR
7421 @throw std::out_of_range if the given vector ends prematurely
7423 @sa https://tools.ietf.org/html/rfc7049
7425 static basic_json from_cbor_internal(const std::vector<uint8_t>& v, size_t& idx)
7427 // store and increment index
7428 const size_t current_idx = idx++;
7430 switch (v.at(current_idx))
7432 // Integer 0x00..0x17 (0..23)
7458 return v[current_idx];
7461 case 0x18: // Unsigned integer (one-byte uint8_t follows)
7463 idx += 1; // skip content byte
7464 return get_from_vector<uint8_t>(v, current_idx);
7467 case 0x19: // Unsigned integer (two-byte uint16_t follows)
7469 idx += 2; // skip 2 content bytes
7470 return get_from_vector<uint16_t>(v, current_idx);
7473 case 0x1a: // Unsigned integer (four-byte uint32_t follows)
7475 idx += 4; // skip 4 content bytes
7476 return get_from_vector<uint32_t>(v, current_idx);
7479 case 0x1b: // Unsigned integer (eight-byte uint64_t follows)
7481 idx += 8; // skip 8 content bytes
7482 return get_from_vector<uint64_t>(v, current_idx);
7485 // Negative integer -1-0x00..-1-0x17 (-1..-24)
7511 return static_cast<int8_t>(0x20 - 1 - v[current_idx]);
7514 case 0x38: // Negative integer (one-byte uint8_t follows)
7516 idx += 1; // skip content byte
7517 // must be uint8_t !
7518 return static_cast<number_integer_t>(-1) - get_from_vector<uint8_t>(v, current_idx);
7521 case 0x39: // Negative integer -1-n (two-byte uint16_t follows)
7523 idx += 2; // skip 2 content bytes
7524 return static_cast<number_integer_t>(-1) - get_from_vector<uint16_t>(v, current_idx);
7527 case 0x3a: // Negative integer -1-n (four-byte uint32_t follows)
7529 idx += 4; // skip 4 content bytes
7530 return static_cast<number_integer_t>(-1) - get_from_vector<uint32_t>(v, current_idx);
7533 case 0x3b: // Negative integer -1-n (eight-byte uint64_t follows)
7535 idx += 8; // skip 8 content bytes
7536 return static_cast<number_integer_t>(-1) - static_cast<number_integer_t>(get_from_vector<uint64_t>(v, current_idx));
7539 // UTF-8 string (0x00..0x17 bytes follow)
7565 const auto len = static_cast<size_t>(v[current_idx] - 0x60);
7566 const size_t offset = current_idx + 1;
7567 idx += len; // skip content bytes
7568 check_length(v.size(), len, offset);
7569 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
7572 case 0x78: // UTF-8 string (one-byte uint8_t for n follows)
7574 const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx));
7575 const size_t offset = current_idx + 2;
7576 idx += len + 1; // skip size byte + content bytes
7577 check_length(v.size(), len, offset);
7578 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
7581 case 0x79: // UTF-8 string (two-byte uint16_t for n follow)
7583 const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
7584 const size_t offset = current_idx + 3;
7585 idx += len + 2; // skip 2 size bytes + content bytes
7586 check_length(v.size(), len, offset);
7587 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
7590 case 0x7a: // UTF-8 string (four-byte uint32_t for n follow)
7592 const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
7593 const size_t offset = current_idx + 5;
7594 idx += len + 4; // skip 4 size bytes + content bytes
7595 check_length(v.size(), len, offset);
7596 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
7599 case 0x7b: // UTF-8 string (eight-byte uint64_t for n follow)
7601 const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx));
7602 const size_t offset = current_idx + 9;
7603 idx += len + 8; // skip 8 size bytes + content bytes
7604 check_length(v.size(), len, offset);
7605 return std::string(reinterpret_cast<const char*>(v.data()) + offset, len);
7608 case 0x7f: // UTF-8 string (indefinite length)
7611 while (v.at(idx) != 0xff)
7613 string_t s = from_cbor_internal(v, idx);
7616 // skip break byte (0xFF)
7621 // array (0x00..0x17 data items follow)
7647 basic_json result = value_t::array;
7648 const auto len = static_cast<size_t>(v[current_idx] - 0x80);
7649 for (size_t i = 0; i < len; ++i)
7651 result.push_back(from_cbor_internal(v, idx));
7656 case 0x98: // array (one-byte uint8_t for n follows)
7658 basic_json result = value_t::array;
7659 const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx));
7660 idx += 1; // skip 1 size byte
7661 for (size_t i = 0; i < len; ++i)
7663 result.push_back(from_cbor_internal(v, idx));
7668 case 0x99: // array (two-byte uint16_t for n follow)
7670 basic_json result = value_t::array;
7671 const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
7672 idx += 2; // skip 4 size bytes
7673 for (size_t i = 0; i < len; ++i)
7675 result.push_back(from_cbor_internal(v, idx));
7680 case 0x9a: // array (four-byte uint32_t for n follow)
7682 basic_json result = value_t::array;
7683 const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
7684 idx += 4; // skip 4 size bytes
7685 for (size_t i = 0; i < len; ++i)
7687 result.push_back(from_cbor_internal(v, idx));
7692 case 0x9b: // array (eight-byte uint64_t for n follow)
7694 basic_json result = value_t::array;
7695 const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx));
7696 idx += 8; // skip 8 size bytes
7697 for (size_t i = 0; i < len; ++i)
7699 result.push_back(from_cbor_internal(v, idx));
7704 case 0x9f: // array (indefinite length)
7706 basic_json result = value_t::array;
7707 while (v.at(idx) != 0xff)
7709 result.push_back(from_cbor_internal(v, idx));
7711 // skip break byte (0xFF)
7716 // map (0x00..0x17 pairs of data items follow)
7742 basic_json result = value_t::object;
7743 const auto len = static_cast<size_t>(v[current_idx] - 0xa0);
7744 for (size_t i = 0; i < len; ++i)
7746 std::string key = from_cbor_internal(v, idx);
7747 result[key] = from_cbor_internal(v, idx);
7752 case 0xb8: // map (one-byte uint8_t for n follows)
7754 basic_json result = value_t::object;
7755 const auto len = static_cast<size_t>(get_from_vector<uint8_t>(v, current_idx));
7756 idx += 1; // skip 1 size byte
7757 for (size_t i = 0; i < len; ++i)
7759 std::string key = from_cbor_internal(v, idx);
7760 result[key] = from_cbor_internal(v, idx);
7765 case 0xb9: // map (two-byte uint16_t for n follow)
7767 basic_json result = value_t::object;
7768 const auto len = static_cast<size_t>(get_from_vector<uint16_t>(v, current_idx));
7769 idx += 2; // skip 2 size bytes
7770 for (size_t i = 0; i < len; ++i)
7772 std::string key = from_cbor_internal(v, idx);
7773 result[key] = from_cbor_internal(v, idx);
7778 case 0xba: // map (four-byte uint32_t for n follow)
7780 basic_json result = value_t::object;
7781 const auto len = static_cast<size_t>(get_from_vector<uint32_t>(v, current_idx));
7782 idx += 4; // skip 4 size bytes
7783 for (size_t i = 0; i < len; ++i)
7785 std::string key = from_cbor_internal(v, idx);
7786 result[key] = from_cbor_internal(v, idx);
7791 case 0xbb: // map (eight-byte uint64_t for n follow)
7793 basic_json result = value_t::object;
7794 const auto len = static_cast<size_t>(get_from_vector<uint64_t>(v, current_idx));
7795 idx += 8; // skip 8 size bytes
7796 for (size_t i = 0; i < len; ++i)
7798 std::string key = from_cbor_internal(v, idx);
7799 result[key] = from_cbor_internal(v, idx);
7804 case 0xbf: // map (indefinite length)
7806 basic_json result = value_t::object;
7807 while (v.at(idx) != 0xff)
7809 std::string key = from_cbor_internal(v, idx);
7810 result[key] = from_cbor_internal(v, idx);
7812 // skip break byte (0xFF)
7829 return value_t::null;
7832 case 0xf9: // Half-Precision Float (two-byte IEEE 754)
7834 idx += 2; // skip two content bytes
7836 // code from RFC 7049, Appendix D, Figure 3:
7837 // As half-precision floating-point numbers were only added to
7838 // IEEE 754 in 2008, today's programming platforms often still
7839 // only have limited support for them. It is very easy to
7840 // include at least decoding support for them even without such
7841 // support. An example of a small decoder for half-precision
7842 // floating-point numbers in the C language is shown in Fig. 3.
7843 const int half = (v.at(current_idx + 1) << 8) + v.at(current_idx + 2);
7844 const int exp = (half >> 10) & 0x1f;
7845 const int mant = half & 0x3ff;
7849 val = std::ldexp(mant, -24);
7853 val = std::ldexp(mant + 1024, exp - 25);
7858 ? std::numeric_limits<double>::infinity()
7859 : std::numeric_limits<double>::quiet_NaN();
7861 return (half & 0x8000) != 0 ? -val : val;
7864 case 0xfa: // Single-Precision Float (four-byte IEEE 754)
7866 // copy bytes in reverse order into the float variable
7868 for (size_t byte = 0; byte < sizeof(float); ++byte)
7870 reinterpret_cast<uint8_t*>(&res)[sizeof(float) - byte - 1] = v.at(current_idx + 1 + byte);
7872 idx += sizeof(float); // skip content bytes
7876 case 0xfb: // Double-Precision Float (eight-byte IEEE 754)
7878 // copy bytes in reverse order into the double variable
7880 for (size_t byte = 0; byte < sizeof(double); ++byte)
7882 reinterpret_cast<uint8_t*>(&res)[sizeof(double) - byte - 1] = v.at(current_idx + 1 + byte);
7884 idx += sizeof(double); // skip content bytes
7888 default: // anything else (0xFF is handled inside the other types)
7890 JSON_THROW(std::invalid_argument("error parsing a CBOR @ " + std::to_string(current_idx) + ": " + std::to_string(static_cast<int>(v[current_idx]))));
7897 @brief create a MessagePack serialization of a given JSON value
7899 Serializes a given JSON value @a j to a byte vector using the MessagePack
7900 serialization format. MessagePack is a binary serialization format which
7901 aims to be more compact than JSON itself, yet more efficient to parse.
7903 @param[in] j JSON value to serialize
7904 @return MessagePack serialization as byte vector
7906 @complexity Linear in the size of the JSON value @a j.
7908 @liveexample{The example shows the serialization of a JSON value to a byte
7909 vector in MessagePack format.,to_msgpack}
7911 @sa http://msgpack.org
7912 @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the
7913 analogous deserialization
7914 @sa @ref to_cbor(const basic_json& for the related CBOR format
7916 @since version 2.0.9
7918 static std::vector<uint8_t> to_msgpack(const basic_json& j)
7920 std::vector<uint8_t> result;
7921 to_msgpack_internal(j, result);
7926 @brief create a JSON value from a byte vector in MessagePack format
7928 Deserializes a given byte vector @a v to a JSON value using the MessagePack
7929 serialization format.
7931 @param[in] v a byte vector in MessagePack format
7932 @param[in] start_index the index to start reading from @a v (0 by default)
7933 @return deserialized JSON value
7935 @throw std::invalid_argument if unsupported features from MessagePack were
7936 used in the given vector @a v or if the input is not valid MessagePack
7937 @throw std::out_of_range if the given vector ends prematurely
7939 @complexity Linear in the size of the byte vector @a v.
7941 @liveexample{The example shows the deserialization of a byte vector in
7942 MessagePack format to a JSON value.,from_msgpack}
7944 @sa http://msgpack.org
7945 @sa @ref to_msgpack(const basic_json&) for the analogous serialization
7946 @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the
7949 @since version 2.0.9, parameter @a start_index since 2.1.1
7951 static basic_json from_msgpack(const std::vector<uint8_t>& v,
7952 const size_t start_index = 0)
7954 size_t i = start_index;
7955 return from_msgpack_internal(v, i);
7959 @brief create a MessagePack serialization of a given JSON value
7961 Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
7962 Binary Object Representation) serialization format. CBOR is a binary
7963 serialization format which aims to be more compact than JSON itself, yet
7964 more efficient to parse.
7966 @param[in] j JSON value to serialize
7967 @return MessagePack serialization as byte vector
7969 @complexity Linear in the size of the JSON value @a j.
7971 @liveexample{The example shows the serialization of a JSON value to a byte
7972 vector in CBOR format.,to_cbor}
7975 @sa @ref from_cbor(const std::vector<uint8_t>&, const size_t) for the
7976 analogous deserialization
7977 @sa @ref to_msgpack(const basic_json& for the related MessagePack format
7979 @since version 2.0.9
7981 static std::vector<uint8_t> to_cbor(const basic_json& j)
7983 std::vector<uint8_t> result;
7984 to_cbor_internal(j, result);
7989 @brief create a JSON value from a byte vector in CBOR format
7991 Deserializes a given byte vector @a v to a JSON value using the CBOR
7992 (Concise Binary Object Representation) serialization format.
7994 @param[in] v a byte vector in CBOR format
7995 @param[in] start_index the index to start reading from @a v (0 by default)
7996 @return deserialized JSON value
7998 @throw std::invalid_argument if unsupported features from CBOR were used in
7999 the given vector @a v or if the input is not valid MessagePack
8000 @throw std::out_of_range if the given vector ends prematurely
8002 @complexity Linear in the size of the byte vector @a v.
8004 @liveexample{The example shows the deserialization of a byte vector in CBOR
8005 format to a JSON value.,from_cbor}
8008 @sa @ref to_cbor(const basic_json&) for the analogous serialization
8009 @sa @ref from_msgpack(const std::vector<uint8_t>&, const size_t) for the
8010 related MessagePack format
8012 @since version 2.0.9, parameter @a start_index since 2.1.1
8014 static basic_json from_cbor(const std::vector<uint8_t>& v,
8015 const size_t start_index = 0)
8017 size_t i = start_index;
8018 return from_cbor_internal(v, i);
8023 ///////////////////////////
8024 // convenience functions //
8025 ///////////////////////////
8028 @brief return the type as string
8030 Returns the type name as string to be used in error messages - usually to
8031 indicate that a function was called on a wrong JSON type.
8033 @return basically a string representation of a the @a m_type member
8035 @complexity Constant.
8037 @liveexample{The following code exemplifies `type_name()` for all JSON
8040 @since version 1.0.0, public since 2.1.0
8042 std::string type_name() const
8049 case value_t::object:
8051 case value_t::array:
8053 case value_t::string:
8055 case value_t::boolean:
8057 case value_t::discarded:
8067 @brief calculates the extra space to escape a JSON string
8069 @param[in] s the string to escape
8070 @return the number of characters required to escape string @a s
8072 @complexity Linear in the length of string @a s.
8074 static std::size_t extra_space(const string_t& s) noexcept
8076 return std::accumulate(s.begin(), s.end(), size_t{},
8077 [](size_t res, typename string_t::value_type c)
8089 // from c (1 byte) to \x (2 bytes)
8095 if (c >= 0x00 and c <= 0x1f)
8097 // from c (1 byte) to \uxxxx (6 bytes)
8108 @brief escape a string
8110 Escape a string by replacing certain special characters by a sequence of
8111 an escape character (backslash) and another character and other control
8112 characters by a sequence of "\u" followed by a four-digit hex
8115 @param[in] s the string to escape
8116 @return the escaped string
8118 @complexity Linear in the length of string @a s.
8120 static string_t escape_string(const string_t& s)
8122 const auto space = extra_space(s);
8128 // create a result string of necessary size
8129 string_t result(s.size() + space, '\\');
8130 std::size_t pos = 0;
8132 for (const auto& c : s)
8136 // quotation mark (0x22)
8139 result[pos + 1] = '"';
8144 // reverse solidus (0x5c)
8147 // nothing to change
8155 result[pos + 1] = 'b';
8163 result[pos + 1] = 'f';
8171 result[pos + 1] = 'n';
8176 // carriage return (0x0d)
8179 result[pos + 1] = 'r';
8184 // horizontal tab (0x09)
8187 result[pos + 1] = 't';
8194 if (c >= 0x00 and c <= 0x1f)
8196 // convert a number 0..15 to its hex representation
8198 static const char hexify[16] =
8200 '0', '1', '2', '3', '4', '5', '6', '7',
8201 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
8204 // print character c as \uxxxx
8206 { 'u', '0', '0', hexify[c >> 4], hexify[c & 0x0f]
8216 // all other characters are added as-is
8229 @brief locale-independent serialization for built-in arithmetic types
8234 template<typename NumberType>
8235 numtostr(NumberType value)
8237 x_write(value, std::is_integral<NumberType>());
8240 const char* c_str() const
8242 return m_buf.data();
8246 /// a (hopefully) large enough character buffer
8247 std::array < char, 64 > m_buf{{}};
8249 template<typename NumberType>
8250 void x_write(NumberType x, /*is_integral=*/std::true_type)
8252 // special case for "0"
8259 const bool is_negative = x < 0;
8262 // spare 1 byte for '\0'
8263 while (x != 0 and i < m_buf.size() - 1)
8265 const auto digit = std::labs(static_cast<long>(x % 10));
8266 m_buf[i++] = static_cast<char>('0' + digit);
8270 // make sure the number has been processed completely
8275 // make sure there is capacity for the '-'
8276 assert(i < m_buf.size() - 2);
8280 std::reverse(m_buf.begin(), m_buf.begin() + i);
8283 template<typename NumberType>
8284 void x_write(NumberType x, /*is_integral=*/std::false_type)
8286 // special case for 0.0 and -0.0
8290 if (std::signbit(x))
8300 // get number of digits for a text -> float -> text round-trip
8301 static constexpr auto d = std::numeric_limits<NumberType>::digits10;
8303 // the actual conversion
8304 const auto written_bytes = snprintf(m_buf.data(), m_buf.size(), "%.*g", d, (double)x);
8306 // negative value indicates an error
8307 assert(written_bytes > 0);
8308 // check if buffer was large enough
8309 assert(static_cast<size_t>(written_bytes) < m_buf.size());
8311 // read information from locale
8312 const auto loc = localeconv();
8313 assert(loc != nullptr);
8314 const char thousands_sep = !loc->thousands_sep ? '\0'
8315 : loc->thousands_sep[0];
8317 const char decimal_point = !loc->decimal_point ? '\0'
8318 : loc->decimal_point[0];
8320 // erase thousands separator
8321 if (thousands_sep != '\0')
8323 const auto end = std::remove(m_buf.begin(), m_buf.begin() + written_bytes, thousands_sep);
8324 std::fill(end, m_buf.end(), '\0');
8327 // convert decimal point to '.'
8328 if (decimal_point != '\0' and decimal_point != '.')
8330 for (auto& c : m_buf)
8332 if (c == decimal_point)
8340 // determine if need to append ".0"
8342 bool value_is_int_like = true;
8343 for (i = 0; i < m_buf.size(); ++i)
8345 // break when end of number is reached
8346 if (m_buf[i] == '\0')
8351 // check if we find non-int character
8352 value_is_int_like = value_is_int_like and m_buf[i] != '.' and
8353 m_buf[i] != 'e' and m_buf[i] != 'E';
8356 if (value_is_int_like)
8358 // there must be 2 bytes left for ".0"
8359 assert((i + 2) < m_buf.size());
8360 // we write to the end of the number
8361 assert(m_buf[i] == '\0');
8362 assert(m_buf[i - 1] != '\0');
8368 // the resulting string is properly terminated
8369 assert(m_buf[i + 2] == '\0');
8376 @brief internal implementation of the serialization function
8378 This function is called by the public member function dump and organizes
8379 the serialization internally. The indentation level is propagated as
8380 additional parameter. In case of arrays and objects, the function is
8381 called recursively. Note that
8383 - strings and object keys are escaped using `escape_string()`
8384 - integer numbers are converted implicitly via `operator<<`
8385 - floating-point numbers are converted to a string using `"%g"` format
8387 @param[out] o stream to write to
8388 @param[in] pretty_print whether the output shall be pretty-printed
8389 @param[in] indent_step the indent level
8390 @param[in] current_indent the current indent level (only used internally)
8392 void dump(std::ostream& o,
8393 const bool pretty_print,
8394 const unsigned int indent_step,
8395 const unsigned int current_indent = 0) const
8397 // variable to hold indentation for recursive calls
8398 unsigned int new_indent = current_indent;
8402 case value_t::object:
8404 if (m_value.object->empty())
8412 // increase indentation
8415 new_indent += indent_step;
8419 for (auto i = m_value.object->cbegin(); i != m_value.object->cend(); ++i)
8421 if (i != m_value.object->cbegin())
8423 o << (pretty_print ? ",\n" : ",");
8425 o << string_t(new_indent, ' ') << "\""
8426 << escape_string(i->first) << "\":"
8427 << (pretty_print ? " " : "");
8428 i->second.dump(o, pretty_print, indent_step, new_indent);
8431 // decrease indentation
8434 new_indent -= indent_step;
8438 o << string_t(new_indent, ' ') + "}";
8442 case value_t::array:
8444 if (m_value.array->empty())
8452 // increase indentation
8455 new_indent += indent_step;
8459 for (auto i = m_value.array->cbegin(); i != m_value.array->cend(); ++i)
8461 if (i != m_value.array->cbegin())
8463 o << (pretty_print ? ",\n" : ",");
8465 o << string_t(new_indent, ' ');
8466 i->dump(o, pretty_print, indent_step, new_indent);
8469 // decrease indentation
8472 new_indent -= indent_step;
8476 o << string_t(new_indent, ' ') << "]";
8480 case value_t::string:
8482 o << string_t("\"") << escape_string(*m_value.string) << "\"";
8486 case value_t::boolean:
8488 o << (m_value.boolean ? "true" : "false");
8492 case value_t::number_integer:
8494 o << numtostr(m_value.number_integer).c_str();
8498 case value_t::number_unsigned:
8500 o << numtostr(m_value.number_unsigned).c_str();
8504 case value_t::number_float:
8506 o << numtostr(m_value.number_float).c_str();
8510 case value_t::discarded:
8525 //////////////////////
8526 // member variables //
8527 //////////////////////
8529 /// the type of the current element
8530 value_t m_type = value_t::null;
8532 /// the value of the current element
8533 json_value m_value = {};
8542 @brief an iterator for primitive JSON types
8544 This class models an iterator for primitive JSON types (boolean, number,
8545 string). It's only purpose is to allow the iterator/const_iterator classes
8546 to "iterate" over primitive values. Internally, the iterator is modeled by
8547 a `difference_type` variable. Value begin_value (`0`) models the begin,
8548 end_value (`1`) models past the end.
8550 class primitive_iterator_t
8554 difference_type get_value() const noexcept
8558 /// set iterator to a defined beginning
8559 void set_begin() noexcept
8564 /// set iterator to a defined past the end
8565 void set_end() noexcept
8570 /// return whether the iterator can be dereferenced
8571 constexpr bool is_begin() const noexcept
8573 return (m_it == begin_value);
8576 /// return whether the iterator is at end
8577 constexpr bool is_end() const noexcept
8579 return (m_it == end_value);
8582 friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
8584 return lhs.m_it == rhs.m_it;
8587 friend constexpr bool operator!=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
8589 return !(lhs == rhs);
8592 friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
8594 return lhs.m_it < rhs.m_it;
8597 friend constexpr bool operator<=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
8599 return lhs.m_it <= rhs.m_it;
8602 friend constexpr bool operator>(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
8604 return lhs.m_it > rhs.m_it;
8607 friend constexpr bool operator>=(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
8609 return lhs.m_it >= rhs.m_it;
8612 primitive_iterator_t operator+(difference_type i)
8614 auto result = *this;
8619 friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept
8621 return lhs.m_it - rhs.m_it;
8624 friend std::ostream& operator<<(std::ostream& os, primitive_iterator_t it)
8626 return os << it.m_it;
8629 primitive_iterator_t& operator++()
8635 primitive_iterator_t operator++(int)
8637 auto result = *this;
8642 primitive_iterator_t& operator--()
8648 primitive_iterator_t operator--(int)
8650 auto result = *this;
8655 primitive_iterator_t& operator+=(difference_type n)
8661 primitive_iterator_t& operator-=(difference_type n)
8668 static constexpr difference_type begin_value = 0;
8669 static constexpr difference_type end_value = begin_value + 1;
8671 /// iterator as signed integer type
8672 difference_type m_it = std::numeric_limits<std::ptrdiff_t>::denorm_min();
8676 @brief an iterator value
8678 @note This structure could easily be a union, but MSVC currently does not
8679 allow unions members with complex constructors, see
8680 https://github.com/nlohmann/json/pull/105.
8682 struct internal_iterator
8684 /// iterator for JSON objects
8685 typename object_t::iterator object_iterator;
8686 /// iterator for JSON arrays
8687 typename array_t::iterator array_iterator;
8688 /// generic iterator for all other types
8689 primitive_iterator_t primitive_iterator;
8691 /// create an uninitialized internal_iterator
8692 internal_iterator() noexcept
8693 : object_iterator(), array_iterator(), primitive_iterator()
8697 /// proxy class for the iterator_wrapper functions
8698 template<typename IteratorType>
8699 class iteration_proxy
8702 /// helper class for iteration
8703 class iteration_proxy_internal
8707 IteratorType anchor;
8708 /// an index for arrays (used to create key names)
8709 size_t array_index = 0;
8712 explicit iteration_proxy_internal(IteratorType it) noexcept
8716 /// dereference operator (needed for range-based for)
8717 iteration_proxy_internal& operator*()
8722 /// increment operator (needed for range-based for)
8723 iteration_proxy_internal& operator++()
8731 /// inequality operator (needed for range-based for)
8732 bool operator!= (const iteration_proxy_internal& o) const
8734 return anchor != o.anchor;
8737 /// return key of the iterator
8738 typename basic_json::string_t key() const
8740 assert(anchor.m_object != nullptr);
8742 switch (anchor.m_object->type())
8744 // use integer array index as key
8745 case value_t::array:
8747 return std::to_string(array_index);
8750 // use key from the object
8751 case value_t::object:
8753 return anchor.key();
8756 // use an empty key for all primitive types
8764 /// return value of the iterator
8765 typename IteratorType::reference value() const
8767 return anchor.value();
8771 /// the container to iterate
8772 typename IteratorType::reference container;
8775 /// construct iteration proxy from a container
8776 explicit iteration_proxy(typename IteratorType::reference cont)
8780 /// return iterator begin (needed for range-based for)
8781 iteration_proxy_internal begin() noexcept
8783 return iteration_proxy_internal(container.begin());
8786 /// return iterator end (needed for range-based for)
8787 iteration_proxy_internal end() noexcept
8789 return iteration_proxy_internal(container.end());
8795 @brief a template for a random access iterator for the @ref basic_json class
8797 This class implements a both iterators (iterator and const_iterator) for the
8798 @ref basic_json class.
8800 @note An iterator is called *initialized* when a pointer to a JSON value
8801 has been set (e.g., by a constructor or a copy assignment). If the
8802 iterator is default-constructed, it is *uninitialized* and most
8803 methods are undefined. **The library uses assertions to detect calls
8804 on uninitialized iterators.**
8806 @requirement The class satisfies the following concept requirements:
8807 - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
8808 The iterator that can be moved to point (forward and backward) to any
8809 element in constant time.
8811 @since version 1.0.0, simplified in version 2.0.9
8813 template<typename U>
8814 class iter_impl : public std::iterator<std::random_access_iterator_tag, U>
8816 /// allow basic_json to access private members
8817 friend class basic_json;
8819 // make sure U is basic_json or const basic_json
8820 static_assert(std::is_same<U, basic_json>::value
8821 or std::is_same<U, const basic_json>::value,
8822 "iter_impl only accepts (const) basic_json");
8825 /// the type of the values when the iterator is dereferenced
8826 using value_type = typename basic_json::value_type;
8827 /// a type to represent differences between iterators
8828 using difference_type = typename basic_json::difference_type;
8829 /// defines a pointer to the type iterated over (value_type)
8830 using pointer = typename std::conditional<std::is_const<U>::value,
8831 typename basic_json::const_pointer,
8832 typename basic_json::pointer>::type;
8833 /// defines a reference to the type iterated over (value_type)
8834 using reference = typename std::conditional<std::is_const<U>::value,
8835 typename basic_json::const_reference,
8836 typename basic_json::reference>::type;
8837 /// the category of the iterator
8838 using iterator_category = std::bidirectional_iterator_tag;
8840 /// default constructor
8841 iter_impl() = default;
8844 @brief constructor for a given JSON instance
8845 @param[in] object pointer to a JSON object for this iterator
8846 @pre object != nullptr
8847 @post The iterator is initialized; i.e. `m_object != nullptr`.
8849 explicit iter_impl(pointer object) noexcept
8852 assert(m_object != nullptr);
8854 switch (m_object->m_type)
8856 case basic_json::value_t::object:
8858 m_it.object_iterator = typename object_t::iterator();
8862 case basic_json::value_t::array:
8864 m_it.array_iterator = typename array_t::iterator();
8870 m_it.primitive_iterator = primitive_iterator_t();
8877 Use operator `const_iterator` instead of `const_iterator(const iterator&
8878 other) noexcept` to avoid two class definitions for @ref iterator and
8879 @ref const_iterator.
8881 This function is only called if this class is an @ref iterator. If this
8882 class is a @ref const_iterator this function is not called.
8884 operator const_iterator() const
8890 ret.m_object = m_object;
8898 @brief copy constructor
8899 @param[in] other iterator to copy from
8900 @note It is not checked whether @a other is initialized.
8902 iter_impl(const iter_impl& other) noexcept
8903 : m_object(other.m_object), m_it(other.m_it)
8907 @brief copy assignment
8908 @param[in,out] other iterator to copy from
8909 @note It is not checked whether @a other is initialized.
8911 iter_impl& operator=(iter_impl other) noexcept(
8912 std::is_nothrow_move_constructible<pointer>::value and
8913 std::is_nothrow_move_assignable<pointer>::value and
8914 std::is_nothrow_move_constructible<internal_iterator>::value and
8915 std::is_nothrow_move_assignable<internal_iterator>::value
8918 std::swap(m_object, other.m_object);
8919 std::swap(m_it, other.m_it);
8925 @brief set the iterator to the first value
8926 @pre The iterator is initialized; i.e. `m_object != nullptr`.
8928 void set_begin() noexcept
8930 assert(m_object != nullptr);
8932 switch (m_object->m_type)
8934 case basic_json::value_t::object:
8936 m_it.object_iterator = m_object->m_value.object->begin();
8940 case basic_json::value_t::array:
8942 m_it.array_iterator = m_object->m_value.array->begin();
8946 case basic_json::value_t::null:
8948 // set to end so begin()==end() is true: null is empty
8949 m_it.primitive_iterator.set_end();
8955 m_it.primitive_iterator.set_begin();
8962 @brief set the iterator past the last value
8963 @pre The iterator is initialized; i.e. `m_object != nullptr`.
8965 void set_end() noexcept
8967 assert(m_object != nullptr);
8969 switch (m_object->m_type)
8971 case basic_json::value_t::object:
8973 m_it.object_iterator = m_object->m_value.object->end();
8977 case basic_json::value_t::array:
8979 m_it.array_iterator = m_object->m_value.array->end();
8985 m_it.primitive_iterator.set_end();
8993 @brief return a reference to the value pointed to by the iterator
8994 @pre The iterator is initialized; i.e. `m_object != nullptr`.
8996 reference operator*() const
8998 assert(m_object != nullptr);
9000 switch (m_object->m_type)
9002 case basic_json::value_t::object:
9004 assert(m_it.object_iterator != m_object->m_value.object->end());
9005 return m_it.object_iterator->second;
9008 case basic_json::value_t::array:
9010 assert(m_it.array_iterator != m_object->m_value.array->end());
9011 return *m_it.array_iterator;
9014 case basic_json::value_t::null:
9016 JSON_THROW(std::out_of_range("cannot get value"));
9021 if (m_it.primitive_iterator.is_begin())
9026 JSON_THROW(std::out_of_range("cannot get value"));
9032 @brief dereference the iterator
9033 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9035 pointer operator->() const
9037 assert(m_object != nullptr);
9039 switch (m_object->m_type)
9041 case basic_json::value_t::object:
9043 assert(m_it.object_iterator != m_object->m_value.object->end());
9044 return &(m_it.object_iterator->second);
9047 case basic_json::value_t::array:
9049 assert(m_it.array_iterator != m_object->m_value.array->end());
9050 return &*m_it.array_iterator;
9055 if (m_it.primitive_iterator.is_begin())
9060 JSON_THROW(std::out_of_range("cannot get value"));
9066 @brief post-increment (it++)
9067 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9069 iter_impl operator++(int)
9071 auto result = *this;
9077 @brief pre-increment (++it)
9078 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9080 iter_impl& operator++()
9082 assert(m_object != nullptr);
9084 switch (m_object->m_type)
9086 case basic_json::value_t::object:
9088 std::advance(m_it.object_iterator, 1);
9092 case basic_json::value_t::array:
9094 std::advance(m_it.array_iterator, 1);
9100 ++m_it.primitive_iterator;
9109 @brief post-decrement (it--)
9110 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9112 iter_impl operator--(int)
9114 auto result = *this;
9120 @brief pre-decrement (--it)
9121 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9123 iter_impl& operator--()
9125 assert(m_object != nullptr);
9127 switch (m_object->m_type)
9129 case basic_json::value_t::object:
9131 std::advance(m_it.object_iterator, -1);
9135 case basic_json::value_t::array:
9137 std::advance(m_it.array_iterator, -1);
9143 --m_it.primitive_iterator;
9152 @brief comparison: equal
9153 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9155 bool operator==(const iter_impl& other) const
9157 // if objects are not the same, the comparison is undefined
9158 if (m_object != other.m_object)
9160 JSON_THROW(std::domain_error("cannot compare iterators of different containers"));
9163 assert(m_object != nullptr);
9165 switch (m_object->m_type)
9167 case basic_json::value_t::object:
9169 return (m_it.object_iterator == other.m_it.object_iterator);
9172 case basic_json::value_t::array:
9174 return (m_it.array_iterator == other.m_it.array_iterator);
9179 return (m_it.primitive_iterator == other.m_it.primitive_iterator);
9185 @brief comparison: not equal
9186 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9188 bool operator!=(const iter_impl& other) const
9190 return not operator==(other);
9194 @brief comparison: smaller
9195 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9197 bool operator<(const iter_impl& other) const
9199 // if objects are not the same, the comparison is undefined
9200 if (m_object != other.m_object)
9202 JSON_THROW(std::domain_error("cannot compare iterators of different containers"));
9205 assert(m_object != nullptr);
9207 switch (m_object->m_type)
9209 case basic_json::value_t::object:
9211 JSON_THROW(std::domain_error("cannot compare order of object iterators"));
9214 case basic_json::value_t::array:
9216 return (m_it.array_iterator < other.m_it.array_iterator);
9221 return (m_it.primitive_iterator < other.m_it.primitive_iterator);
9227 @brief comparison: less than or equal
9228 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9230 bool operator<=(const iter_impl& other) const
9232 return not other.operator < (*this);
9236 @brief comparison: greater than
9237 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9239 bool operator>(const iter_impl& other) const
9241 return not operator<=(other);
9245 @brief comparison: greater than or equal
9246 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9248 bool operator>=(const iter_impl& other) const
9250 return not operator<(other);
9254 @brief add to iterator
9255 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9257 iter_impl& operator+=(difference_type i)
9259 assert(m_object != nullptr);
9261 switch (m_object->m_type)
9263 case basic_json::value_t::object:
9265 JSON_THROW(std::domain_error("cannot use offsets with object iterators"));
9268 case basic_json::value_t::array:
9270 std::advance(m_it.array_iterator, i);
9276 m_it.primitive_iterator += i;
9285 @brief subtract from iterator
9286 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9288 iter_impl& operator-=(difference_type i)
9290 return operator+=(-i);
9294 @brief add to iterator
9295 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9297 iter_impl operator+(difference_type i)
9299 auto result = *this;
9305 @brief subtract from iterator
9306 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9308 iter_impl operator-(difference_type i)
9310 auto result = *this;
9316 @brief return difference
9317 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9319 difference_type operator-(const iter_impl& other) const
9321 assert(m_object != nullptr);
9323 switch (m_object->m_type)
9325 case basic_json::value_t::object:
9327 JSON_THROW(std::domain_error("cannot use offsets with object iterators"));
9330 case basic_json::value_t::array:
9332 return m_it.array_iterator - other.m_it.array_iterator;
9337 return m_it.primitive_iterator - other.m_it.primitive_iterator;
9343 @brief access to successor
9344 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9346 reference operator[](difference_type n) const
9348 assert(m_object != nullptr);
9350 switch (m_object->m_type)
9352 case basic_json::value_t::object:
9354 JSON_THROW(std::domain_error("cannot use operator[] for object iterators"));
9357 case basic_json::value_t::array:
9359 return *std::next(m_it.array_iterator, n);
9362 case basic_json::value_t::null:
9364 JSON_THROW(std::out_of_range("cannot get value"));
9369 if (m_it.primitive_iterator.get_value() == -n)
9374 JSON_THROW(std::out_of_range("cannot get value"));
9380 @brief return the key of an object iterator
9381 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9383 typename object_t::key_type key() const
9385 assert(m_object != nullptr);
9387 if (m_object->is_object())
9389 return m_it.object_iterator->first;
9392 JSON_THROW(std::domain_error("cannot use key() for non-object iterators"));
9396 @brief return the value of an iterator
9397 @pre The iterator is initialized; i.e. `m_object != nullptr`.
9399 reference value() const
9405 /// associated JSON instance
9406 pointer m_object = nullptr;
9407 /// the actual iterator of the associated instance
9408 internal_iterator m_it = internal_iterator();
9412 @brief a template for a reverse iterator class
9414 @tparam Base the base iterator type to reverse. Valid types are @ref
9415 iterator (to create @ref reverse_iterator) and @ref const_iterator (to
9416 create @ref const_reverse_iterator).
9418 @requirement The class satisfies the following concept requirements:
9419 - [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
9420 The iterator that can be moved to point (forward and backward) to any
9421 element in constant time.
9422 - [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
9423 It is possible to write to the pointed-to element (only if @a Base is
9426 @since version 1.0.0
9428 template<typename Base>
9429 class json_reverse_iterator : public std::reverse_iterator<Base>
9432 /// shortcut to the reverse iterator adaptor
9433 using base_iterator = std::reverse_iterator<Base>;
9434 /// the reference type for the pointed-to element
9435 using reference = typename Base::reference;
9437 /// create reverse iterator from iterator
9438 json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept
9442 /// create reverse iterator from base class
9443 json_reverse_iterator(const base_iterator& it) noexcept
9447 /// post-increment (it++)
9448 json_reverse_iterator operator++(int)
9450 return base_iterator::operator++(1);
9453 /// pre-increment (++it)
9454 json_reverse_iterator& operator++()
9456 base_iterator::operator++();
9460 /// post-decrement (it--)
9461 json_reverse_iterator operator--(int)
9463 return base_iterator::operator--(1);
9466 /// pre-decrement (--it)
9467 json_reverse_iterator& operator--()
9469 base_iterator::operator--();
9474 json_reverse_iterator& operator+=(difference_type i)
9476 base_iterator::operator+=(i);
9481 json_reverse_iterator operator+(difference_type i) const
9483 auto result = *this;
9488 /// subtract from iterator
9489 json_reverse_iterator operator-(difference_type i) const
9491 auto result = *this;
9496 /// return difference
9497 difference_type operator-(const json_reverse_iterator& other) const
9499 return this->base() - other.base();
9502 /// access to successor
9503 reference operator[](difference_type n) const
9505 return *(this->operator+(n));
9508 /// return the key of an object iterator
9509 typename object_t::key_type key() const
9511 auto it = --this->base();
9515 /// return the value of an iterator
9516 reference value() const
9518 auto it = --this->base();
9519 return it.operator * ();
9525 //////////////////////
9526 // lexer and parser //
9527 //////////////////////
9530 @brief lexical analysis
9532 This class organizes the lexical analysis during JSON deserialization. The
9533 core of it is a scanner generated by [re2c](http://re2c.org) that
9534 processes a buffer and recognizes tokens according to RFC 7159.
9539 /// token types for the parser
9540 enum class token_type
9542 uninitialized, ///< indicating the scanner is uninitialized
9543 literal_true, ///< the `true` literal
9544 literal_false, ///< the `false` literal
9545 literal_null, ///< the `null` literal
9546 value_string, ///< a string -- use get_string() for actual value
9547 value_unsigned, ///< an unsigned integer -- use get_number() for actual value
9548 value_integer, ///< a signed integer -- use get_number() for actual value
9549 value_float, ///< an floating point number -- use get_number() for actual value
9550 begin_array, ///< the character for array begin `[`
9551 begin_object, ///< the character for object begin `{`
9552 end_array, ///< the character for array end `]`
9553 end_object, ///< the character for object end `}`
9554 name_separator, ///< the name separator `:`
9555 value_separator, ///< the value separator `,`
9556 parse_error, ///< indicating a parse error
9557 end_of_input ///< indicating the end of the input buffer
9560 /// the char type to use in the lexer
9561 using lexer_char_t = unsigned char;
9563 /// a lexer from a buffer with given length
9564 lexer(const lexer_char_t* buff, const size_t len) noexcept
9567 assert(m_content != nullptr);
9568 m_start = m_cursor = m_content;
9569 m_limit = m_content + len;
9572 /// a lexer from an input stream
9573 explicit lexer(std::istream& s)
9574 : m_stream(&s), m_line_buffer()
9576 // immediately abort if stream is erroneous
9579 JSON_THROW(std::invalid_argument("stream error"));
9585 // skip UTF-8 byte-order mark
9586 if (m_line_buffer.size() >= 3 and m_line_buffer.substr(0, 3) == "\xEF\xBB\xBF")
9588 m_line_buffer[0] = ' ';
9589 m_line_buffer[1] = ' ';
9590 m_line_buffer[2] = ' ';
9594 // switch off unwanted functions (due to pointer members)
9596 lexer(const lexer&) = delete;
9597 lexer operator=(const lexer&) = delete;
9600 @brief create a string from one or two Unicode code points
9602 There are two cases: (1) @a codepoint1 is in the Basic Multilingual
9603 Plane (U+0000 through U+FFFF) and @a codepoint2 is 0, or (2)
9604 @a codepoint1 and @a codepoint2 are a UTF-16 surrogate pair to
9605 represent a code point above U+FFFF.
9607 @param[in] codepoint1 the code point (can be high surrogate)
9608 @param[in] codepoint2 the code point (can be low surrogate or 0)
9610 @return string representation of the code point; the length of the
9611 result string is between 1 and 4 characters.
9613 @throw std::out_of_range if code point is > 0x10ffff; example: `"code
9614 points above 0x10FFFF are invalid"`
9615 @throw std::invalid_argument if the low surrogate is invalid; example:
9616 `""missing or wrong low surrogate""`
9618 @complexity Constant.
9620 @see <http://en.wikipedia.org/wiki/UTF-8#Sample_code>
9622 static string_t to_unicode(const std::size_t codepoint1,
9623 const std::size_t codepoint2 = 0)
9625 // calculate the code point from the given code points
9626 std::size_t codepoint = codepoint1;
9628 // check if codepoint1 is a high surrogate
9629 if (codepoint1 >= 0xD800 and codepoint1 <= 0xDBFF)
9631 // check if codepoint2 is a low surrogate
9632 if (codepoint2 >= 0xDC00 and codepoint2 <= 0xDFFF)
9635 // high surrogate occupies the most significant 22 bits
9637 // low surrogate occupies the least significant 15 bits
9639 // there is still the 0xD800, 0xDC00 and 0x10000 noise
9640 // in the result so we have to subtract with:
9641 // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
9646 JSON_THROW(std::invalid_argument("missing or wrong low surrogate"));
9652 if (codepoint < 0x80)
9654 // 1-byte characters: 0xxxxxxx (ASCII)
9655 result.append(1, static_cast<typename string_t::value_type>(codepoint));
9657 else if (codepoint <= 0x7ff)
9659 // 2-byte characters: 110xxxxx 10xxxxxx
9660 result.append(1, static_cast<typename string_t::value_type>(0xC0 | ((codepoint >> 6) & 0x1F)));
9661 result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
9663 else if (codepoint <= 0xffff)
9665 // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
9666 result.append(1, static_cast<typename string_t::value_type>(0xE0 | ((codepoint >> 12) & 0x0F)));
9667 result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F)));
9668 result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
9670 else if (codepoint <= 0x10ffff)
9672 // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
9673 result.append(1, static_cast<typename string_t::value_type>(0xF0 | ((codepoint >> 18) & 0x07)));
9674 result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 12) & 0x3F)));
9675 result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F)));
9676 result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
9680 JSON_THROW(std::out_of_range("code points above 0x10FFFF are invalid"));
9686 /// return name of values of type token_type (only used for errors)
9687 static std::string token_type_name(const token_type t)
9691 case token_type::uninitialized:
9692 return "<uninitialized>";
9693 case token_type::literal_true:
9694 return "true literal";
9695 case token_type::literal_false:
9696 return "false literal";
9697 case token_type::literal_null:
9698 return "null literal";
9699 case token_type::value_string:
9700 return "string literal";
9701 case lexer::token_type::value_unsigned:
9702 case lexer::token_type::value_integer:
9703 case lexer::token_type::value_float:
9704 return "number literal";
9705 case token_type::begin_array:
9707 case token_type::begin_object:
9709 case token_type::end_array:
9711 case token_type::end_object:
9713 case token_type::name_separator:
9715 case token_type::value_separator:
9717 case token_type::parse_error:
9718 return "<parse error>";
9719 case token_type::end_of_input:
9720 return "end of input";
9723 // catch non-enum values
9724 return "unknown token"; // LCOV_EXCL_LINE
9730 This function implements a scanner for JSON. It is specified using
9731 regular expressions that try to follow RFC 7159 as close as possible.
9732 These regular expressions are then translated into a minimized
9733 deterministic finite automaton (DFA) by the tool
9734 [re2c](http://re2c.org). As a result, the translated code for this
9735 function consists of a large block of code with `goto` jumps.
9737 @return the class of the next token read from the buffer
9739 @complexity Linear in the length of the input.\n
9741 Proposition: The loop below will always terminate for finite input.\n
9743 Proof (by contradiction): Assume a finite input. To loop forever, the
9744 loop must never hit code with a `break` statement. The only code
9745 snippets without a `break` statement are the continue statements for
9746 whitespace and byte-order-marks. To loop forever, the input must be an
9747 infinite sequence of whitespace or byte-order-marks. This contradicts
9748 the assumption of finite input, q.e.d.
9754 // pointer for backtracking information
9757 // remember the begin of the token
9759 assert(m_start != nullptr);
9764 unsigned int yyaccept = 0;
9765 static const unsigned char yybm[] =
9767 0, 0, 0, 0, 0, 0, 0, 0,
9768 0, 32, 32, 0, 0, 32, 0, 0,
9769 0, 0, 0, 0, 0, 0, 0, 0,
9770 0, 0, 0, 0, 0, 0, 0, 0,
9771 160, 128, 0, 128, 128, 128, 128, 128,
9772 128, 128, 128, 128, 128, 128, 128, 128,
9773 192, 192, 192, 192, 192, 192, 192, 192,
9774 192, 192, 128, 128, 128, 128, 128, 128,
9775 128, 128, 128, 128, 128, 128, 128, 128,
9776 128, 128, 128, 128, 128, 128, 128, 128,
9777 128, 128, 128, 128, 128, 128, 128, 128,
9778 128, 128, 128, 128, 0, 128, 128, 128,
9779 128, 128, 128, 128, 128, 128, 128, 128,
9780 128, 128, 128, 128, 128, 128, 128, 128,
9781 128, 128, 128, 128, 128, 128, 128, 128,
9782 128, 128, 128, 128, 128, 128, 128, 128,
9783 0, 0, 0, 0, 0, 0, 0, 0,
9784 0, 0, 0, 0, 0, 0, 0, 0,
9785 0, 0, 0, 0, 0, 0, 0, 0,
9786 0, 0, 0, 0, 0, 0, 0, 0,
9787 0, 0, 0, 0, 0, 0, 0, 0,
9788 0, 0, 0, 0, 0, 0, 0, 0,
9789 0, 0, 0, 0, 0, 0, 0, 0,
9790 0, 0, 0, 0, 0, 0, 0, 0,
9791 0, 0, 0, 0, 0, 0, 0, 0,
9792 0, 0, 0, 0, 0, 0, 0, 0,
9793 0, 0, 0, 0, 0, 0, 0, 0,
9794 0, 0, 0, 0, 0, 0, 0, 0,
9795 0, 0, 0, 0, 0, 0, 0, 0,
9796 0, 0, 0, 0, 0, 0, 0, 0,
9797 0, 0, 0, 0, 0, 0, 0, 0,
9798 0, 0, 0, 0, 0, 0, 0, 0,
9800 if ((m_limit - m_cursor) < 5)
9802 fill_line_buffer(5); // LCOV_EXCL_LINE
9805 if (yybm[0 + yych] & 32)
9807 goto basic_json_parser_6;
9817 goto basic_json_parser_2;
9821 goto basic_json_parser_4;
9823 goto basic_json_parser_9;
9829 goto basic_json_parser_4;
9833 goto basic_json_parser_10;
9835 goto basic_json_parser_12;
9844 goto basic_json_parser_4;
9848 goto basic_json_parser_13;
9850 goto basic_json_parser_15;
9856 goto basic_json_parser_17;
9860 goto basic_json_parser_4;
9862 goto basic_json_parser_19;
9874 goto basic_json_parser_21;
9876 goto basic_json_parser_4;
9882 goto basic_json_parser_23;
9886 goto basic_json_parser_4;
9888 goto basic_json_parser_24;
9897 goto basic_json_parser_25;
9899 goto basic_json_parser_4;
9905 goto basic_json_parser_26;
9909 goto basic_json_parser_28;
9911 goto basic_json_parser_4;
9915 basic_json_parser_2:
9918 last_token_type = token_type::end_of_input;
9921 basic_json_parser_4:
9923 basic_json_parser_5:
9925 last_token_type = token_type::parse_error;
9928 basic_json_parser_6:
9930 if (m_limit <= m_cursor)
9932 fill_line_buffer(1); // LCOV_EXCL_LINE
9935 if (yybm[0 + yych] & 32)
9937 goto basic_json_parser_6;
9942 basic_json_parser_9:
9944 yych = *(m_marker = ++m_cursor);
9947 goto basic_json_parser_5;
9951 goto basic_json_parser_31;
9955 goto basic_json_parser_5;
9959 goto basic_json_parser_31;
9961 goto basic_json_parser_5;
9962 basic_json_parser_10:
9965 last_token_type = token_type::value_separator;
9968 basic_json_parser_12:
9972 goto basic_json_parser_5;
9976 goto basic_json_parser_43;
9980 goto basic_json_parser_45;
9982 goto basic_json_parser_5;
9983 basic_json_parser_13:
9985 yych = *(m_marker = ++m_cursor);
9990 goto basic_json_parser_47;
9994 goto basic_json_parser_48;
10003 goto basic_json_parser_51;
10010 goto basic_json_parser_51;
10014 basic_json_parser_14:
10016 last_token_type = token_type::value_unsigned;
10019 basic_json_parser_15:
10021 m_marker = ++m_cursor;
10022 if ((m_limit - m_cursor) < 3)
10024 fill_line_buffer(3); // LCOV_EXCL_LINE
10027 if (yybm[0 + yych] & 64)
10029 goto basic_json_parser_15;
10035 goto basic_json_parser_47;
10037 goto basic_json_parser_14;
10043 goto basic_json_parser_51;
10047 goto basic_json_parser_51;
10049 goto basic_json_parser_14;
10051 basic_json_parser_17:
10054 last_token_type = token_type::name_separator;
10057 basic_json_parser_19:
10060 last_token_type = token_type::begin_array;
10063 basic_json_parser_21:
10066 last_token_type = token_type::end_array;
10069 basic_json_parser_23:
10071 yych = *(m_marker = ++m_cursor);
10074 goto basic_json_parser_52;
10076 goto basic_json_parser_5;
10077 basic_json_parser_24:
10079 yych = *(m_marker = ++m_cursor);
10082 goto basic_json_parser_53;
10084 goto basic_json_parser_5;
10085 basic_json_parser_25:
10087 yych = *(m_marker = ++m_cursor);
10090 goto basic_json_parser_54;
10092 goto basic_json_parser_5;
10093 basic_json_parser_26:
10096 last_token_type = token_type::begin_object;
10099 basic_json_parser_28:
10102 last_token_type = token_type::end_object;
10105 basic_json_parser_30:
10107 if (m_limit <= m_cursor)
10109 fill_line_buffer(1); // LCOV_EXCL_LINE
10112 basic_json_parser_31:
10113 if (yybm[0 + yych] & 128)
10115 goto basic_json_parser_30;
10123 goto basic_json_parser_32;
10127 goto basic_json_parser_33;
10129 goto basic_json_parser_35;
10135 goto basic_json_parser_32;
10139 goto basic_json_parser_36;
10141 goto basic_json_parser_37;
10150 goto basic_json_parser_39;
10152 goto basic_json_parser_38;
10158 goto basic_json_parser_40;
10162 goto basic_json_parser_41;
10166 goto basic_json_parser_42;
10170 basic_json_parser_32:
10171 m_cursor = m_marker;
10176 goto basic_json_parser_5;
10180 goto basic_json_parser_14;
10187 goto basic_json_parser_44;
10191 goto basic_json_parser_58;
10194 basic_json_parser_33:
10197 last_token_type = token_type::value_string;
10200 basic_json_parser_35:
10202 if (m_limit <= m_cursor)
10204 fill_line_buffer(1); // LCOV_EXCL_LINE
10213 goto basic_json_parser_30;
10217 goto basic_json_parser_32;
10219 goto basic_json_parser_30;
10227 goto basic_json_parser_32;
10229 goto basic_json_parser_30;
10235 goto basic_json_parser_30;
10237 goto basic_json_parser_32;
10247 goto basic_json_parser_30;
10251 goto basic_json_parser_30;
10253 goto basic_json_parser_32;
10261 goto basic_json_parser_30;
10263 goto basic_json_parser_32;
10269 goto basic_json_parser_30;
10273 goto basic_json_parser_55;
10275 goto basic_json_parser_32;
10279 basic_json_parser_36:
10281 if (m_limit <= m_cursor)
10283 fill_line_buffer(1); // LCOV_EXCL_LINE
10288 goto basic_json_parser_32;
10292 goto basic_json_parser_30;
10294 goto basic_json_parser_32;
10295 basic_json_parser_37:
10297 if (m_limit <= m_cursor)
10299 fill_line_buffer(1); // LCOV_EXCL_LINE
10304 goto basic_json_parser_32;
10308 goto basic_json_parser_36;
10310 goto basic_json_parser_32;
10311 basic_json_parser_38:
10313 if (m_limit <= m_cursor)
10315 fill_line_buffer(1); // LCOV_EXCL_LINE
10320 goto basic_json_parser_32;
10324 goto basic_json_parser_36;
10326 goto basic_json_parser_32;
10327 basic_json_parser_39:
10329 if (m_limit <= m_cursor)
10331 fill_line_buffer(1); // LCOV_EXCL_LINE
10336 goto basic_json_parser_32;
10340 goto basic_json_parser_36;
10342 goto basic_json_parser_32;
10343 basic_json_parser_40:
10345 if (m_limit <= m_cursor)
10347 fill_line_buffer(1); // LCOV_EXCL_LINE
10352 goto basic_json_parser_32;
10356 goto basic_json_parser_38;
10358 goto basic_json_parser_32;
10359 basic_json_parser_41:
10361 if (m_limit <= m_cursor)
10363 fill_line_buffer(1); // LCOV_EXCL_LINE
10368 goto basic_json_parser_32;
10372 goto basic_json_parser_38;
10374 goto basic_json_parser_32;
10375 basic_json_parser_42:
10377 if (m_limit <= m_cursor)
10379 fill_line_buffer(1); // LCOV_EXCL_LINE
10384 goto basic_json_parser_32;
10388 goto basic_json_parser_38;
10390 goto basic_json_parser_32;
10391 basic_json_parser_43:
10393 yych = *(m_marker = ++m_cursor);
10398 goto basic_json_parser_47;
10402 goto basic_json_parser_48;
10411 goto basic_json_parser_51;
10418 goto basic_json_parser_51;
10422 basic_json_parser_44:
10424 last_token_type = token_type::value_integer;
10427 basic_json_parser_45:
10429 m_marker = ++m_cursor;
10430 if ((m_limit - m_cursor) < 3)
10432 fill_line_buffer(3); // LCOV_EXCL_LINE
10439 goto basic_json_parser_47;
10443 goto basic_json_parser_44;
10445 goto basic_json_parser_45;
10453 goto basic_json_parser_44;
10455 goto basic_json_parser_51;
10461 goto basic_json_parser_51;
10463 goto basic_json_parser_44;
10466 basic_json_parser_47:
10467 yych = *++m_cursor;
10470 goto basic_json_parser_32;
10474 goto basic_json_parser_56;
10476 goto basic_json_parser_32;
10477 basic_json_parser_48:
10479 if (m_limit <= m_cursor)
10481 fill_line_buffer(1); // LCOV_EXCL_LINE
10486 goto basic_json_parser_50;
10490 goto basic_json_parser_48;
10492 basic_json_parser_50:
10494 last_token_type = token_type::parse_error;
10497 basic_json_parser_51:
10498 yych = *++m_cursor;
10503 goto basic_json_parser_59;
10505 goto basic_json_parser_32;
10511 goto basic_json_parser_59;
10515 goto basic_json_parser_32;
10519 goto basic_json_parser_60;
10521 goto basic_json_parser_32;
10523 basic_json_parser_52:
10524 yych = *++m_cursor;
10527 goto basic_json_parser_62;
10529 goto basic_json_parser_32;
10530 basic_json_parser_53:
10531 yych = *++m_cursor;
10534 goto basic_json_parser_63;
10536 goto basic_json_parser_32;
10537 basic_json_parser_54:
10538 yych = *++m_cursor;
10541 goto basic_json_parser_64;
10543 goto basic_json_parser_32;
10544 basic_json_parser_55:
10546 if (m_limit <= m_cursor)
10548 fill_line_buffer(1); // LCOV_EXCL_LINE
10555 goto basic_json_parser_32;
10559 goto basic_json_parser_65;
10561 goto basic_json_parser_32;
10567 goto basic_json_parser_65;
10571 goto basic_json_parser_32;
10575 goto basic_json_parser_65;
10577 goto basic_json_parser_32;
10579 basic_json_parser_56:
10581 m_marker = ++m_cursor;
10582 if ((m_limit - m_cursor) < 3)
10584 fill_line_buffer(3); // LCOV_EXCL_LINE
10591 goto basic_json_parser_58;
10595 goto basic_json_parser_56;
10602 goto basic_json_parser_51;
10606 goto basic_json_parser_51;
10609 basic_json_parser_58:
10611 last_token_type = token_type::value_float;
10614 basic_json_parser_59:
10615 yych = *++m_cursor;
10618 goto basic_json_parser_32;
10622 goto basic_json_parser_32;
10624 basic_json_parser_60:
10626 if (m_limit <= m_cursor)
10628 fill_line_buffer(1); // LCOV_EXCL_LINE
10633 goto basic_json_parser_58;
10637 goto basic_json_parser_60;
10639 goto basic_json_parser_58;
10640 basic_json_parser_62:
10641 yych = *++m_cursor;
10644 goto basic_json_parser_66;
10646 goto basic_json_parser_32;
10647 basic_json_parser_63:
10648 yych = *++m_cursor;
10651 goto basic_json_parser_67;
10653 goto basic_json_parser_32;
10654 basic_json_parser_64:
10655 yych = *++m_cursor;
10658 goto basic_json_parser_69;
10660 goto basic_json_parser_32;
10661 basic_json_parser_65:
10663 if (m_limit <= m_cursor)
10665 fill_line_buffer(1); // LCOV_EXCL_LINE
10672 goto basic_json_parser_32;
10676 goto basic_json_parser_71;
10678 goto basic_json_parser_32;
10684 goto basic_json_parser_71;
10688 goto basic_json_parser_32;
10692 goto basic_json_parser_71;
10694 goto basic_json_parser_32;
10696 basic_json_parser_66:
10697 yych = *++m_cursor;
10700 goto basic_json_parser_72;
10702 goto basic_json_parser_32;
10703 basic_json_parser_67:
10706 last_token_type = token_type::literal_null;
10709 basic_json_parser_69:
10712 last_token_type = token_type::literal_true;
10715 basic_json_parser_71:
10717 if (m_limit <= m_cursor)
10719 fill_line_buffer(1); // LCOV_EXCL_LINE
10726 goto basic_json_parser_32;
10730 goto basic_json_parser_74;
10732 goto basic_json_parser_32;
10738 goto basic_json_parser_74;
10742 goto basic_json_parser_32;
10746 goto basic_json_parser_74;
10748 goto basic_json_parser_32;
10750 basic_json_parser_72:
10753 last_token_type = token_type::literal_false;
10756 basic_json_parser_74:
10758 if (m_limit <= m_cursor)
10760 fill_line_buffer(1); // LCOV_EXCL_LINE
10767 goto basic_json_parser_32;
10771 goto basic_json_parser_30;
10773 goto basic_json_parser_32;
10779 goto basic_json_parser_30;
10783 goto basic_json_parser_32;
10787 goto basic_json_parser_30;
10789 goto basic_json_parser_32;
10795 return last_token_type;
10799 @brief append data from the stream to the line buffer
10801 This function is called by the scan() function when the end of the
10802 buffer (`m_limit`) is reached and the `m_cursor` pointer cannot be
10803 incremented without leaving the limits of the line buffer. Note re2c
10804 decides when to call this function.
10806 If the lexer reads from contiguous storage, there is no trailing null
10807 byte. Therefore, this function must make sure to add these padding
10810 If the lexer reads from an input stream, this function reads the next
10814 p p p p p p u u u u u x . . . . . .
10816 m_content m_start | m_limit
10820 u u u u u x x x x x x x . . . . . .
10826 void fill_line_buffer(size_t n = 0)
10828 // if line buffer is used, m_content points to its data
10829 assert(m_line_buffer.empty()
10830 or m_content == reinterpret_cast<const lexer_char_t*>(m_line_buffer.data()));
10832 // if line buffer is used, m_limit is set past the end of its data
10833 assert(m_line_buffer.empty()
10834 or m_limit == m_content + m_line_buffer.size());
10836 // pointer relationships
10837 assert(m_content <= m_start);
10838 assert(m_start <= m_cursor);
10839 assert(m_cursor <= m_limit);
10840 assert(m_marker == nullptr or m_marker <= m_limit);
10842 // number of processed characters (p)
10843 const auto num_processed_chars = static_cast<size_t>(m_start - m_content);
10844 // offset for m_marker wrt. to m_start
10845 const auto offset_marker = (m_marker == nullptr) ? 0 : m_marker - m_start;
10846 // number of unprocessed characters (u)
10847 const auto offset_cursor = m_cursor - m_start;
10849 // no stream is used or end of file is reached
10850 if (m_stream == nullptr or m_stream->eof())
10852 // m_start may or may not be pointing into m_line_buffer at
10853 // this point. We trust the standard library to do the right
10854 // thing. See http://stackoverflow.com/q/28142011/266378
10855 m_line_buffer.assign(m_start, m_limit);
10857 // append n characters to make sure that there is sufficient
10858 // space between m_cursor and m_limit
10859 m_line_buffer.append(1, '\x00');
10862 m_line_buffer.append(n - 1, '\x01');
10867 // delete processed characters from line buffer
10868 m_line_buffer.erase(0, num_processed_chars);
10869 // read next line from input stream
10870 m_line_buffer_tmp.clear();
10871 std::getline(*m_stream, m_line_buffer_tmp, '\n');
10873 // add line with newline symbol to the line buffer
10874 m_line_buffer += m_line_buffer_tmp;
10875 m_line_buffer.push_back('\n');
10879 m_content = reinterpret_cast<const lexer_char_t*>(m_line_buffer.data());
10880 assert(m_content != nullptr);
10881 m_start = m_content;
10882 m_marker = m_start + offset_marker;
10883 m_cursor = m_start + offset_cursor;
10884 m_limit = m_start + m_line_buffer.size();
10887 /// return string representation of last read token
10888 string_t get_token_string() const
10890 assert(m_start != nullptr);
10891 return string_t(reinterpret_cast<typename string_t::const_pointer>(m_start),
10892 static_cast<size_t>(m_cursor - m_start));
10896 @brief return string value for string tokens
10898 The function iterates the characters between the opening and closing
10899 quotes of the string value. The complete string is the range
10900 [m_start,m_cursor). Consequently, we iterate from m_start+1 to
10903 We differentiate two cases:
10905 1. Escaped characters. In this case, a new character is constructed
10906 according to the nature of the escape. Some escapes create new
10907 characters (e.g., `"\\n"` is replaced by `"\n"`), some are copied
10908 as is (e.g., `"\\\\"`). Furthermore, Unicode escapes of the shape
10909 `"\\uxxxx"` need special care. In this case, to_unicode takes care
10910 of the construction of the values.
10911 2. Unescaped characters are copied as is.
10913 @pre `m_cursor - m_start >= 2`, meaning the length of the last token
10914 is at least 2 bytes which is trivially true for any string (which
10915 consists of at least two quotes).
10921 @complexity Linear in the length of the string.\n
10923 Lemma: The loop body will always terminate.\n
10925 Proof (by contradiction): Assume the loop body does not terminate. As
10926 the loop body does not contain another loop, one of the called
10927 functions must never return. The called functions are `std::strtoul`
10928 and to_unicode. Neither function can loop forever, so the loop body
10929 will never loop forever which contradicts the assumption that the loop
10930 body does not terminate, q.e.d.\n
10932 Lemma: The loop condition for the for loop is eventually false.\n
10934 Proof (by contradiction): Assume the loop does not terminate. Due to
10935 the above lemma, this can only be due to a tautological loop
10936 condition; that is, the loop condition i < m_cursor - 1 must always be
10937 true. Let x be the change of i for any loop iteration. Then
10938 m_start + 1 + x < m_cursor - 1 must hold to loop indefinitely. This
10939 can be rephrased to m_cursor - m_start - 2 > x. With the
10940 precondition, we x <= 0, meaning that the loop condition holds
10941 indefinitely if i is always decreased. However, observe that the value
10942 of i is strictly increasing with each iteration, as it is incremented
10943 by 1 in the iteration expression and never decremented inside the loop
10944 body. Hence, the loop condition will eventually be false which
10945 contradicts the assumption that the loop condition is a tautology,
10948 @return string value of current token without opening and closing
10950 @throw std::out_of_range if to_unicode fails
10952 string_t get_string() const
10954 assert(m_cursor - m_start >= 2);
10957 result.reserve(static_cast<size_t>(m_cursor - m_start - 2));
10959 // iterate the result between the quotes
10960 for (const lexer_char_t* i = m_start + 1; i < m_cursor - 1; ++i)
10962 // find next escape character
10963 auto e = std::find(i, m_cursor - 1, '\\');
10966 // see https://github.com/nlohmann/json/issues/365#issuecomment-262874705
10967 for (auto k = i; k < e; k++)
10969 result.push_back(static_cast<typename string_t::value_type>(*k));
10971 i = e - 1; // -1 because of ++i
10975 // processing escaped character
10976 // read next character
10981 // the default escapes
11026 // get code xxxx from uxxxx
11027 auto codepoint = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>(i + 1),
11028 4).c_str(), nullptr, 16);
11030 // check if codepoint is a high surrogate
11031 if (codepoint >= 0xD800 and codepoint <= 0xDBFF)
11033 // make sure there is a subsequent unicode
11034 if ((i + 6 >= m_limit) or * (i + 5) != '\\' or * (i + 6) != 'u')
11036 JSON_THROW(std::invalid_argument("missing low surrogate"));
11039 // get code yyyy from uxxxx\uyyyy
11040 auto codepoint2 = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>
11041 (i + 7), 4).c_str(), nullptr, 16);
11042 result += to_unicode(codepoint, codepoint2);
11043 // skip the next 10 characters (xxxx\uyyyy)
11046 else if (codepoint >= 0xDC00 and codepoint <= 0xDFFF)
11048 // we found a lone low surrogate
11049 JSON_THROW(std::invalid_argument("missing high surrogate"));
11053 // add unicode character(s)
11054 result += to_unicode(codepoint);
11055 // skip the next four characters (xxxx)
11069 @brief parse string into a built-in arithmetic type as if the current
11072 @note in floating-point case strtod may parse past the token's end -
11073 this is not an error
11075 @note any leading blanks are not handled
11080 strtonum(const char* start, const char* end)
11081 : m_start(start), m_end(end)
11085 @return true iff parsed successfully as number of type T
11087 @param[in,out] val shall contain parsed value, or undefined value
11090 template<typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value>::type>
11091 bool to(T& val) const
11093 return parse(val, std::is_integral<T>());
11097 const char* const m_start = nullptr;
11098 const char* const m_end = nullptr;
11100 // floating-point conversion
11102 // overloaded wrappers for strtod/strtof/strtold
11103 // that will be called from parse<floating_point_t>
11104 static void strtof(float& f, const char* str, char** endptr)
11106 f = std::strtof(str, endptr);
11109 static void strtof(double& f, const char* str, char** endptr)
11111 f = std::strtod(str, endptr);
11114 static void strtof(long double& f, const char* str, char** endptr)
11116 f = std::strtold(str, endptr);
11119 template<typename T>
11120 bool parse(T& value, /*is_integral=*/std::false_type) const
11122 // replace decimal separator with locale-specific version,
11123 // when necessary; data will point to either the original
11124 // string, or buf, or tempstr containing the fixed string.
11125 std::string tempstr;
11126 std::array<char, 64> buf;
11127 const size_t len = static_cast<size_t>(m_end - m_start);
11129 // lexer will reject empty numbers
11132 // since dealing with strtod family of functions, we're
11133 // getting the decimal point char from the C locale facilities
11134 // instead of C++'s numpunct facet of the current std::locale
11135 const auto loc = localeconv();
11136 assert(loc != nullptr);
11137 const char decimal_point_char = (loc->decimal_point == nullptr) ? '.' : loc->decimal_point[0];
11139 const char* data = m_start;
11141 if (decimal_point_char != '.')
11143 const size_t ds_pos = static_cast<size_t>(std::find(m_start, m_end, '.') - m_start);
11147 // copy the data into the local buffer or tempstr, if
11148 // buffer is too small; replace decimal separator, and
11149 // update data to point to the modified bytes
11150 if ((len + 1) < buf.size())
11152 std::copy(m_start, m_end, buf.begin());
11154 buf[ds_pos] = decimal_point_char;
11159 tempstr.assign(m_start, m_end);
11160 tempstr[ds_pos] = decimal_point_char;
11161 data = tempstr.c_str();
11166 char* endptr = nullptr;
11168 // this calls appropriate overload depending on T
11169 strtof(value, data, &endptr);
11171 // parsing was successful iff strtof parsed exactly the number
11172 // of characters determined by the lexer (len)
11173 const bool ok = (endptr == (data + len));
11175 if (ok and (value == static_cast<T>(0.0)) and (*data == '-'))
11177 // some implementations forget to negate the zero
11184 // integral conversion
11186 signed long long parse_integral(char** endptr, /*is_signed*/std::true_type) const
11188 return std::strtoll(m_start, endptr, 10);
11191 unsigned long long parse_integral(char** endptr, /*is_signed*/std::false_type) const
11193 return std::strtoull(m_start, endptr, 10);
11196 template<typename T>
11197 bool parse(T& value, /*is_integral=*/std::true_type) const
11199 char* endptr = nullptr;
11200 errno = 0; // these are thread-local
11201 const auto x = parse_integral(&endptr, std::is_signed<T>());
11203 // called right overload?
11204 static_assert(std::is_signed<T>() == std::is_signed<decltype(x)>(), "");
11206 value = static_cast<T>(x);
11208 return (x == static_cast<decltype(x)>(value)) // x fits into destination T
11209 and (x < 0) == (value < 0) // preserved sign
11210 //and ((x != 0) or is_integral()) // strto[u]ll did nto fail
11211 and (errno == 0) // strto[u]ll did not overflow
11212 and (m_start < m_end) // token was not empty
11213 and (endptr == m_end); // parsed entire token exactly
11218 @brief return number value for number tokens
11220 This function translates the last token into the most appropriate
11221 number type (either integer, unsigned integer or floating point),
11222 which is passed back to the caller via the result parameter.
11224 integral numbers that don't fit into the the range of the respective
11225 type are parsed as number_float_t
11227 floating-point values do not satisfy std::isfinite predicate
11228 are converted to value_t::null
11230 throws if the entire string [m_start .. m_cursor) cannot be
11231 interpreted as a number
11233 @param[out] result @ref basic_json object to receive the number.
11234 @param[in] token the type of the number token
11236 bool get_number(basic_json& result, const token_type token) const
11238 assert(m_start != nullptr);
11239 assert(m_start < m_cursor);
11240 assert((token == token_type::value_unsigned) or
11241 (token == token_type::value_integer) or
11242 (token == token_type::value_float));
11244 strtonum num_converter(reinterpret_cast<const char*>(m_start),
11245 reinterpret_cast<const char*>(m_cursor));
11249 case lexer::token_type::value_unsigned:
11251 number_unsigned_t val;
11252 if (num_converter.to(val))
11254 // parsing successful
11255 result.m_type = value_t::number_unsigned;
11256 result.m_value = val;
11262 case lexer::token_type::value_integer:
11264 number_integer_t val;
11265 if (num_converter.to(val))
11267 // parsing successful
11268 result.m_type = value_t::number_integer;
11269 result.m_value = val;
11281 // parse float (either explicitly or because a previous conversion
11283 number_float_t val;
11284 if (num_converter.to(val))
11286 // parsing successful
11287 result.m_type = value_t::number_float;
11288 result.m_value = val;
11290 // replace infinity and NAN by null
11291 if (not std::isfinite(result.m_value.number_float))
11293 result.m_type = value_t::null;
11294 result.m_value = basic_json::json_value();
11300 // couldn't parse number in any format
11305 /// optional input stream
11306 std::istream* m_stream = nullptr;
11307 /// line buffer buffer for m_stream
11308 string_t m_line_buffer {};
11309 /// used for filling m_line_buffer
11310 string_t m_line_buffer_tmp {};
11311 /// the buffer pointer
11312 const lexer_char_t* m_content = nullptr;
11313 /// pointer to the beginning of the current symbol
11314 const lexer_char_t* m_start = nullptr;
11315 /// pointer for backtracking information
11316 const lexer_char_t* m_marker = nullptr;
11317 /// pointer to the current symbol
11318 const lexer_char_t* m_cursor = nullptr;
11319 /// pointer to the end of the buffer
11320 const lexer_char_t* m_limit = nullptr;
11321 /// the last token type
11322 token_type last_token_type = token_type::end_of_input;
11326 @brief syntax analysis
11328 This class implements a recursive decent parser.
11333 /// a parser reading from a string literal
11334 parser(const char* buff, const parser_callback_t cb = nullptr)
11336 m_lexer(reinterpret_cast<const typename lexer::lexer_char_t*>(buff), std::strlen(buff))
11339 /// a parser reading from an input stream
11340 parser(std::istream& is, const parser_callback_t cb = nullptr)
11341 : callback(cb), m_lexer(is)
11344 /// a parser reading from an iterator range with contiguous storage
11345 template<class IteratorType, typename std::enable_if<
11346 std::is_same<typename std::iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value
11349 parser(IteratorType first, IteratorType last, const parser_callback_t cb = nullptr)
11351 m_lexer(reinterpret_cast<const typename lexer::lexer_char_t*>(&(*first)),
11352 static_cast<size_t>(std::distance(first, last)))
11355 /// public parser interface
11358 // read first token
11361 basic_json result = parse_internal(true);
11362 result.assert_invariant();
11364 expect(lexer::token_type::end_of_input);
11366 // return parser result and replace it with null in case the
11367 // top-level value was discarded by the callback function
11368 return result.is_discarded() ? basic_json() : std::move(result);
11372 /// the actual parser
11373 basic_json parse_internal(bool keep)
11375 auto result = basic_json(value_t::discarded);
11377 switch (last_token)
11379 case lexer::token_type::begin_object:
11381 if (keep and (not callback
11382 or ((keep = callback(depth++, parse_event_t::object_start, result)) != 0)))
11384 // explicitly set result to object to cope with {}
11385 result.m_type = value_t::object;
11386 result.m_value = value_t::object;
11392 // closing } -> we are done
11393 if (last_token == lexer::token_type::end_object)
11396 if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
11398 result = basic_json(value_t::discarded);
11403 // no comma is expected here
11404 unexpect(lexer::token_type::value_separator);
11406 // otherwise: parse key-value pairs
11409 // ugly, but could be fixed with loop reorganization
11410 if (last_token == lexer::token_type::value_separator)
11416 expect(lexer::token_type::value_string);
11417 const auto key = m_lexer.get_string();
11419 bool keep_tag = false;
11425 keep_tag = callback(depth, parse_event_t::key, k);
11433 // parse separator (:)
11435 expect(lexer::token_type::name_separator);
11437 // parse and add value
11439 auto value = parse_internal(keep);
11440 if (keep and keep_tag and not value.is_discarded())
11442 result[key] = std::move(value);
11445 while (last_token == lexer::token_type::value_separator);
11448 expect(lexer::token_type::end_object);
11450 if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
11452 result = basic_json(value_t::discarded);
11458 case lexer::token_type::begin_array:
11460 if (keep and (not callback
11461 or ((keep = callback(depth++, parse_event_t::array_start, result)) != 0)))
11463 // explicitly set result to object to cope with []
11464 result.m_type = value_t::array;
11465 result.m_value = value_t::array;
11471 // closing ] -> we are done
11472 if (last_token == lexer::token_type::end_array)
11475 if (callback and not callback(--depth, parse_event_t::array_end, result))
11477 result = basic_json(value_t::discarded);
11482 // no comma is expected here
11483 unexpect(lexer::token_type::value_separator);
11485 // otherwise: parse values
11488 // ugly, but could be fixed with loop reorganization
11489 if (last_token == lexer::token_type::value_separator)
11495 auto value = parse_internal(keep);
11496 if (keep and not value.is_discarded())
11498 result.push_back(std::move(value));
11501 while (last_token == lexer::token_type::value_separator);
11504 expect(lexer::token_type::end_array);
11506 if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
11508 result = basic_json(value_t::discarded);
11514 case lexer::token_type::literal_null:
11517 result.m_type = value_t::null;
11521 case lexer::token_type::value_string:
11523 const auto s = m_lexer.get_string();
11525 result = basic_json(s);
11529 case lexer::token_type::literal_true:
11532 result.m_type = value_t::boolean;
11533 result.m_value = true;
11537 case lexer::token_type::literal_false:
11540 result.m_type = value_t::boolean;
11541 result.m_value = false;
11545 case lexer::token_type::value_unsigned:
11546 case lexer::token_type::value_integer:
11547 case lexer::token_type::value_float:
11549 m_lexer.get_number(result, last_token);
11556 // the last token was unexpected
11557 unexpect(last_token);
11561 if (keep and callback and not callback(depth, parse_event_t::value, result))
11563 result = basic_json(value_t::discarded);
11568 /// get next token from lexer
11569 typename lexer::token_type get_token()
11571 last_token = m_lexer.scan();
11575 void expect(typename lexer::token_type t) const
11577 if (t != last_token)
11579 std::string error_msg = "parse error - unexpected ";
11580 error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token_string() +
11582 lexer::token_type_name(last_token));
11583 error_msg += "; expected " + lexer::token_type_name(t);
11584 JSON_THROW(std::invalid_argument(error_msg));
11588 void unexpect(typename lexer::token_type t) const
11590 if (t == last_token)
11592 std::string error_msg = "parse error - unexpected ";
11593 error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token_string() +
11595 lexer::token_type_name(last_token));
11596 JSON_THROW(std::invalid_argument(error_msg));
11601 /// current level of recursion
11603 /// callback function
11604 const parser_callback_t callback = nullptr;
11605 /// the type of the last read token
11606 typename lexer::token_type last_token = lexer::token_type::uninitialized;
11613 @brief JSON Pointer
11615 A JSON pointer defines a string syntax for identifying a specific value
11616 within a JSON document. It can be used with functions `at` and
11617 `operator[]`. Furthermore, JSON pointers are the base for JSON patches.
11619 @sa [RFC 6901](https://tools.ietf.org/html/rfc6901)
11621 @since version 2.0.0
11625 /// allow basic_json to access private members
11626 friend class basic_json;
11630 @brief create JSON pointer
11632 Create a JSON pointer according to the syntax described in
11633 [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3).
11635 @param[in] s string representing the JSON pointer; if omitted, the
11636 empty string is assumed which references the whole JSON
11639 @throw std::domain_error if reference token is nonempty and does not
11640 begin with a slash (`/`); example: `"JSON pointer must be empty or
11642 @throw std::domain_error if a tilde (`~`) is not followed by `0`
11643 (representing `~`) or `1` (representing `/`); example: `"escape error:
11644 ~ must be followed with 0 or 1"`
11646 @liveexample{The example shows the construction several valid JSON
11647 pointers as well as the exceptional behavior.,json_pointer}
11649 @since version 2.0.0
11651 explicit json_pointer(const std::string& s = "")
11652 : reference_tokens(split(s))
11656 @brief return a string representation of the JSON pointer
11658 @invariant For each JSON pointer `ptr`, it holds:
11660 ptr == json_pointer(ptr.to_string());
11663 @return a string representation of the JSON pointer
11665 @liveexample{The example shows the result of `to_string`.,
11666 json_pointer__to_string}
11668 @since version 2.0.0
11670 std::string to_string() const noexcept
11672 return std::accumulate(reference_tokens.begin(),
11673 reference_tokens.end(), std::string{},
11674 [](const std::string & a, const std::string & b)
11676 return a + "/" + escape(b);
11680 /// @copydoc to_string()
11681 operator std::string() const
11683 return to_string();
11687 /// remove and return last reference pointer
11688 std::string pop_back()
11692 JSON_THROW(std::domain_error("JSON pointer has no parent"));
11695 auto last = reference_tokens.back();
11696 reference_tokens.pop_back();
11700 /// return whether pointer points to the root document
11701 bool is_root() const
11703 return reference_tokens.empty();
11706 json_pointer top() const
11710 JSON_THROW(std::domain_error("JSON pointer has no parent"));
11713 json_pointer result = *this;
11714 result.reference_tokens = {reference_tokens[0]};
11719 @brief create and return a reference to the pointed to value
11721 @complexity Linear in the number of reference tokens.
11723 reference get_and_create(reference j) const
11725 pointer result = &j;
11727 // in case no reference tokens exist, return a reference to the
11728 // JSON value j which will be overwritten by a primitive value
11729 for (const auto& reference_token : reference_tokens)
11731 switch (result->m_type)
11733 case value_t::null:
11735 if (reference_token == "0")
11737 // start a new array if reference token is 0
11738 result = &result->operator[](0);
11742 // start a new object otherwise
11743 result = &result->operator[](reference_token);
11748 case value_t::object:
11750 // create an entry in the object
11751 result = &result->operator[](reference_token);
11755 case value_t::array:
11757 // create an entry in the array
11758 result = &result->operator[](static_cast<size_type>(std::stoi(reference_token)));
11763 The following code is only reached if there exists a
11764 reference token _and_ the current value is primitive. In
11765 this case, we have an error situation, because primitive
11766 values may only occur as single value; that is, with an
11767 empty list of reference tokens.
11771 JSON_THROW(std::domain_error("invalid value to unflatten"));
11780 @brief return a reference to the pointed to value
11782 @note This version does not throw if a value is not present, but tries
11783 to create nested values instead. For instance, calling this function
11784 with pointer `"/this/that"` on a null value is equivalent to calling
11785 `operator[]("this").operator[]("that")` on that value, effectively
11786 changing the null value to an object.
11788 @param[in] ptr a JSON value
11790 @return reference to the JSON value pointed to by the JSON pointer
11792 @complexity Linear in the length of the JSON pointer.
11794 @throw std::out_of_range if the JSON pointer can not be resolved
11795 @throw std::domain_error if an array index begins with '0'
11796 @throw std::invalid_argument if an array index was not a number
11798 reference get_unchecked(pointer ptr) const
11800 for (const auto& reference_token : reference_tokens)
11802 // convert null values to arrays or objects before continuing
11803 if (ptr->m_type == value_t::null)
11805 // check if reference token is a number
11806 const bool nums = std::all_of(reference_token.begin(),
11807 reference_token.end(),
11810 return std::isdigit(x);
11813 // change value to array for numbers or "-" or to object
11815 if (nums or reference_token == "-")
11817 *ptr = value_t::array;
11821 *ptr = value_t::object;
11825 switch (ptr->m_type)
11827 case value_t::object:
11829 // use unchecked object access
11830 ptr = &ptr->operator[](reference_token);
11834 case value_t::array:
11836 // error condition (cf. RFC 6901, Sect. 4)
11837 if (reference_token.size() > 1 and reference_token[0] == '0')
11839 JSON_THROW(std::domain_error("array index must not begin with '0'"));
11842 if (reference_token == "-")
11844 // explicitly treat "-" as index beyond the end
11845 ptr = &ptr->operator[](ptr->m_value.array->size());
11849 // convert array index to number; unchecked access
11850 ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token)));
11857 JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'"));
11865 reference get_checked(pointer ptr) const
11867 for (const auto& reference_token : reference_tokens)
11869 switch (ptr->m_type)
11871 case value_t::object:
11873 // note: at performs range check
11874 ptr = &ptr->at(reference_token);
11878 case value_t::array:
11880 if (reference_token == "-")
11882 // "-" always fails the range check
11883 JSON_THROW(std::out_of_range("array index '-' (" +
11884 std::to_string(ptr->m_value.array->size()) +
11885 ") is out of range"));
11888 // error condition (cf. RFC 6901, Sect. 4)
11889 if (reference_token.size() > 1 and reference_token[0] == '0')
11891 JSON_THROW(std::domain_error("array index must not begin with '0'"));
11894 // note: at performs range check
11895 ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
11901 JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'"));
11910 @brief return a const reference to the pointed to value
11912 @param[in] ptr a JSON value
11914 @return const reference to the JSON value pointed to by the JSON
11917 const_reference get_unchecked(const_pointer ptr) const
11919 for (const auto& reference_token : reference_tokens)
11921 switch (ptr->m_type)
11923 case value_t::object:
11925 // use unchecked object access
11926 ptr = &ptr->operator[](reference_token);
11930 case value_t::array:
11932 if (reference_token == "-")
11934 // "-" cannot be used for const access
11935 JSON_THROW(std::out_of_range("array index '-' (" +
11936 std::to_string(ptr->m_value.array->size()) +
11937 ") is out of range"));
11940 // error condition (cf. RFC 6901, Sect. 4)
11941 if (reference_token.size() > 1 and reference_token[0] == '0')
11943 JSON_THROW(std::domain_error("array index must not begin with '0'"));
11946 // use unchecked array access
11947 ptr = &ptr->operator[](static_cast<size_type>(std::stoi(reference_token)));
11953 JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'"));
11961 const_reference get_checked(const_pointer ptr) const
11963 for (const auto& reference_token : reference_tokens)
11965 switch (ptr->m_type)
11967 case value_t::object:
11969 // note: at performs range check
11970 ptr = &ptr->at(reference_token);
11974 case value_t::array:
11976 if (reference_token == "-")
11978 // "-" always fails the range check
11979 JSON_THROW(std::out_of_range("array index '-' (" +
11980 std::to_string(ptr->m_value.array->size()) +
11981 ") is out of range"));
11984 // error condition (cf. RFC 6901, Sect. 4)
11985 if (reference_token.size() > 1 and reference_token[0] == '0')
11987 JSON_THROW(std::domain_error("array index must not begin with '0'"));
11990 // note: at performs range check
11991 ptr = &ptr->at(static_cast<size_type>(std::stoi(reference_token)));
11997 JSON_THROW(std::out_of_range("unresolved reference token '" + reference_token + "'"));
12005 /// split the string input to reference tokens
12006 static std::vector<std::string> split(const std::string& reference_string)
12008 std::vector<std::string> result;
12010 // special case: empty reference string -> no reference tokens
12011 if (reference_string.empty())
12016 // check if nonempty reference string begins with slash
12017 if (reference_string[0] != '/')
12019 JSON_THROW(std::domain_error("JSON pointer must be empty or begin with '/'"));
12022 // extract the reference tokens:
12023 // - slash: position of the last read slash (or end of string)
12024 // - start: position after the previous slash
12026 // search for the first slash after the first character
12027 size_t slash = reference_string.find_first_of('/', 1),
12028 // set the beginning of the first reference token
12030 // we can stop if start == string::npos+1 = 0
12032 // set the beginning of the next reference token
12033 // (will eventually be 0 if slash == std::string::npos)
12036 slash = reference_string.find_first_of('/', start))
12038 // use the text between the beginning of the reference token
12039 // (start) and the last slash (slash).
12040 auto reference_token = reference_string.substr(start, slash - start);
12042 // check reference tokens are properly escaped
12043 for (size_t pos = reference_token.find_first_of('~');
12044 pos != std::string::npos;
12045 pos = reference_token.find_first_of('~', pos + 1))
12047 assert(reference_token[pos] == '~');
12049 // ~ must be followed by 0 or 1
12050 if (pos == reference_token.size() - 1 or
12051 (reference_token[pos + 1] != '0' and
12052 reference_token[pos + 1] != '1'))
12054 JSON_THROW(std::domain_error("escape error: '~' must be followed with '0' or '1'"));
12058 // finally, store the reference token
12059 unescape(reference_token);
12060 result.push_back(reference_token);
12068 @brief replace all occurrences of a substring by another string
12070 @param[in,out] s the string to manipulate; changed so that all
12071 occurrences of @a f are replaced with @a t
12072 @param[in] f the substring to replace with @a t
12073 @param[in] t the string to replace @a f
12075 @pre The search string @a f must not be empty.
12077 @since version 2.0.0
12079 static void replace_substring(std::string& s,
12080 const std::string& f,
12081 const std::string& t)
12083 assert(not f.empty());
12086 size_t pos = s.find(f); // find first occurrence of f
12087 pos != std::string::npos; // make sure f was found
12088 s.replace(pos, f.size(), t), // replace with t
12089 pos = s.find(f, pos + t.size()) // find next occurrence of f
12093 /// escape tilde and slash
12094 static std::string escape(std::string s)
12096 // escape "~"" to "~0" and "/" to "~1"
12097 replace_substring(s, "~", "~0");
12098 replace_substring(s, "/", "~1");
12102 /// unescape tilde and slash
12103 static void unescape(std::string& s)
12105 // first transform any occurrence of the sequence '~1' to '/'
12106 replace_substring(s, "~1", "/");
12107 // then transform any occurrence of the sequence '~0' to '~'
12108 replace_substring(s, "~0", "~");
12112 @param[in] reference_string the reference string to the current value
12113 @param[in] value the value to consider
12114 @param[in,out] result the result object to insert values to
12116 @note Empty objects or arrays are flattened to `null`.
12118 static void flatten(const std::string& reference_string,
12119 const basic_json& value,
12120 basic_json& result)
12122 switch (value.m_type)
12124 case value_t::array:
12126 if (value.m_value.array->empty())
12128 // flatten empty array as null
12129 result[reference_string] = nullptr;
12133 // iterate array and use index as reference string
12134 for (size_t i = 0; i < value.m_value.array->size(); ++i)
12136 flatten(reference_string + "/" + std::to_string(i),
12137 value.m_value.array->operator[](i), result);
12143 case value_t::object:
12145 if (value.m_value.object->empty())
12147 // flatten empty object as null
12148 result[reference_string] = nullptr;
12152 // iterate object and use keys as reference string
12153 for (const auto& element : *value.m_value.object)
12155 flatten(reference_string + "/" + escape(element.first),
12156 element.second, result);
12164 // add primitive value with its reference string
12165 result[reference_string] = value;
12172 @param[in] value flattened JSON
12174 @return unflattened JSON
12176 static basic_json unflatten(const basic_json& value)
12178 if (not value.is_object())
12180 JSON_THROW(std::domain_error("only objects can be unflattened"));
12185 // iterate the JSON object values
12186 for (const auto& element : *value.m_value.object)
12188 if (not element.second.is_primitive())
12190 JSON_THROW(std::domain_error("values in object must be primitive"));
12193 // assign value to reference pointed to by JSON pointer; Note
12194 // that if the JSON pointer is "" (i.e., points to the whole
12195 // value), function get_and_create returns a reference to
12196 // result itself. An assignment will then create a primitive
12198 json_pointer(element.first).get_and_create(result) = element.second;
12205 friend bool operator==(json_pointer const& lhs,
12206 json_pointer const& rhs) noexcept
12208 return lhs.reference_tokens == rhs.reference_tokens;
12211 friend bool operator!=(json_pointer const& lhs,
12212 json_pointer const& rhs) noexcept
12214 return !(lhs == rhs);
12217 /// the reference tokens
12218 std::vector<std::string> reference_tokens {};
12221 //////////////////////////
12222 // JSON Pointer support //
12223 //////////////////////////
12225 /// @name JSON Pointer functions
12229 @brief access specified element via JSON Pointer
12231 Uses a JSON pointer to retrieve a reference to the respective JSON value.
12232 No bound checking is performed. Similar to @ref operator[](const typename
12233 object_t::key_type&), `null` values are created in arrays and objects if
12237 - If the JSON pointer points to an object key that does not exist, it
12238 is created an filled with a `null` value before a reference to it
12240 - If the JSON pointer points to an array index that does not exist, it
12241 is created an filled with a `null` value before a reference to it
12242 is returned. All indices between the current maximum and the given
12243 index are also filled with `null`.
12244 - The special value `-` is treated as a synonym for the index past the
12247 @param[in] ptr a JSON pointer
12249 @return reference to the element pointed to by @a ptr
12251 @complexity Constant.
12253 @throw std::out_of_range if the JSON pointer can not be resolved
12254 @throw std::domain_error if an array index begins with '0'
12255 @throw std::invalid_argument if an array index was not a number
12257 @liveexample{The behavior is shown in the example.,operatorjson_pointer}
12259 @since version 2.0.0
12261 reference operator[](const json_pointer& ptr)
12263 return ptr.get_unchecked(this);
12267 @brief access specified element via JSON Pointer
12269 Uses a JSON pointer to retrieve a reference to the respective JSON value.
12270 No bound checking is performed. The function does not change the JSON
12271 value; no `null` values are created. In particular, the the special value
12272 `-` yields an exception.
12274 @param[in] ptr JSON pointer to the desired element
12276 @return const reference to the element pointed to by @a ptr
12278 @complexity Constant.
12280 @throw std::out_of_range if the JSON pointer can not be resolved
12281 @throw std::domain_error if an array index begins with '0'
12282 @throw std::invalid_argument if an array index was not a number
12284 @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
12286 @since version 2.0.0
12288 const_reference operator[](const json_pointer& ptr) const
12290 return ptr.get_unchecked(this);
12294 @brief access specified element via JSON Pointer
12296 Returns a reference to the element at with specified JSON pointer @a ptr,
12297 with bounds checking.
12299 @param[in] ptr JSON pointer to the desired element
12301 @return reference to the element pointed to by @a ptr
12303 @complexity Constant.
12305 @throw std::out_of_range if the JSON pointer can not be resolved
12306 @throw std::domain_error if an array index begins with '0'
12307 @throw std::invalid_argument if an array index was not a number
12309 @liveexample{The behavior is shown in the example.,at_json_pointer}
12311 @since version 2.0.0
12313 reference at(const json_pointer& ptr)
12315 return ptr.get_checked(this);
12319 @brief access specified element via JSON Pointer
12321 Returns a const reference to the element at with specified JSON pointer @a
12322 ptr, with bounds checking.
12324 @param[in] ptr JSON pointer to the desired element
12326 @return reference to the element pointed to by @a ptr
12328 @complexity Constant.
12330 @throw std::out_of_range if the JSON pointer can not be resolved
12331 @throw std::domain_error if an array index begins with '0'
12332 @throw std::invalid_argument if an array index was not a number
12334 @liveexample{The behavior is shown in the example.,at_json_pointer_const}
12336 @since version 2.0.0
12338 const_reference at(const json_pointer& ptr) const
12340 return ptr.get_checked(this);
12344 @brief return flattened JSON value
12346 The function creates a JSON object whose keys are JSON pointers (see [RFC
12347 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
12348 primitive. The original JSON value can be restored using the @ref
12349 unflatten() function.
12351 @return an object that maps JSON pointers to primitive values
12353 @note Empty objects and arrays are flattened to `null` and will not be
12354 reconstructed correctly by the @ref unflatten() function.
12356 @complexity Linear in the size the JSON value.
12358 @liveexample{The following code shows how a JSON object is flattened to an
12359 object whose keys consist of JSON pointers.,flatten}
12361 @sa @ref unflatten() for the reverse function
12363 @since version 2.0.0
12365 basic_json flatten() const
12367 basic_json result(value_t::object);
12368 json_pointer::flatten("", *this, result);
12373 @brief unflatten a previously flattened JSON value
12375 The function restores the arbitrary nesting of a JSON value that has been
12376 flattened before using the @ref flatten() function. The JSON value must
12377 meet certain constraints:
12378 1. The value must be an object.
12379 2. The keys must be JSON pointers (see
12380 [RFC 6901](https://tools.ietf.org/html/rfc6901))
12381 3. The mapped values must be primitive JSON types.
12383 @return the original JSON from a flattened version
12385 @note Empty objects and arrays are flattened by @ref flatten() to `null`
12386 values and can not unflattened to their original type. Apart from
12387 this example, for a JSON value `j`, the following is always true:
12388 `j == j.flatten().unflatten()`.
12390 @complexity Linear in the size the JSON value.
12392 @liveexample{The following code shows how a flattened JSON object is
12393 unflattened into the original nested JSON object.,unflatten}
12395 @sa @ref flatten() for the reverse function
12397 @since version 2.0.0
12399 basic_json unflatten() const
12401 return json_pointer::unflatten(*this);
12406 //////////////////////////
12407 // JSON Patch functions //
12408 //////////////////////////
12410 /// @name JSON Patch functions
12414 @brief applies a JSON patch
12416 [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
12417 expressing a sequence of operations to apply to a JSON) document. With
12418 this function, a JSON Patch is applied to the current JSON value by
12419 executing all operations from the patch.
12421 @param[in] json_patch JSON patch document
12422 @return patched document
12424 @note The application of a patch is atomic: Either all operations succeed
12425 and the patched document is returned or an exception is thrown. In
12426 any case, the original value is not changed: the patch is applied
12427 to a copy of the value.
12429 @throw std::out_of_range if a JSON pointer inside the patch could not
12430 be resolved successfully in the current JSON value; example: `"key baz
12432 @throw invalid_argument if the JSON patch is malformed (e.g., mandatory
12433 attributes are missing); example: `"operation add must have member path"`
12435 @complexity Linear in the size of the JSON value and the length of the
12436 JSON patch. As usually only a fraction of the JSON value is affected by
12437 the patch, the complexity can usually be neglected.
12439 @liveexample{The following code shows how a JSON patch is applied to a
12442 @sa @ref diff -- create a JSON patch by comparing two JSON values
12444 @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
12445 @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
12447 @since version 2.0.0
12449 basic_json patch(const basic_json& json_patch) const
12451 // make a working copy to apply the patch to
12452 basic_json result = *this;
12454 // the valid JSON Patch operations
12455 enum class patch_operations {add, remove, replace, move, copy, test, invalid};
12457 const auto get_op = [](const std::string op)
12461 return patch_operations::add;
12463 if (op == "remove")
12465 return patch_operations::remove;
12467 if (op == "replace")
12469 return patch_operations::replace;
12473 return patch_operations::move;
12477 return patch_operations::copy;
12481 return patch_operations::test;
12484 return patch_operations::invalid;
12487 // wrapper for "add" operation; add value at ptr
12488 const auto operation_add = [&result](json_pointer & ptr, basic_json val)
12490 // adding to the root of the target document means replacing it
12497 // make sure the top element of the pointer exists
12498 json_pointer top_pointer = ptr.top();
12499 if (top_pointer != ptr)
12501 result.at(top_pointer);
12504 // get reference to parent of JSON pointer ptr
12505 const auto last_path = ptr.pop_back();
12506 basic_json& parent = result[ptr];
12508 switch (parent.m_type)
12510 case value_t::null:
12511 case value_t::object:
12513 // use operator[] to add value
12514 parent[last_path] = val;
12518 case value_t::array:
12520 if (last_path == "-")
12522 // special case: append to back
12523 parent.push_back(val);
12527 const auto idx = std::stoi(last_path);
12528 if (static_cast<size_type>(idx) > parent.size())
12530 // avoid undefined behavior
12531 JSON_THROW(std::out_of_range("array index " + std::to_string(idx) + " is out of range"));
12535 // default case: insert add offset
12536 parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
12544 // if there exists a parent it cannot be primitive
12545 assert(false); // LCOV_EXCL_LINE
12551 // wrapper for "remove" operation; remove value at ptr
12552 const auto operation_remove = [&result](json_pointer & ptr)
12554 // get reference to parent of JSON pointer ptr
12555 const auto last_path = ptr.pop_back();
12556 basic_json& parent = result.at(ptr);
12559 if (parent.is_object())
12561 // perform range check
12562 auto it = parent.find(last_path);
12563 if (it != parent.end())
12569 JSON_THROW(std::out_of_range("key '" + last_path + "' not found"));
12572 else if (parent.is_array())
12574 // note erase performs range check
12575 parent.erase(static_cast<size_type>(std::stoi(last_path)));
12580 if (not json_patch.is_array())
12582 // a JSON patch must be an array of objects
12583 JSON_THROW(std::invalid_argument("JSON patch must be an array of objects"));
12586 // iterate and apply the operations
12587 for (const auto& val : json_patch)
12589 // wrapper to get a value for an operation
12590 const auto get_value = [&val](const std::string & op,
12591 const std::string & member,
12592 bool string_type) -> basic_json&
12595 auto it = val.m_value.object->find(member);
12597 // context-sensitive error message
12598 const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
12600 // check if desired value is present
12601 if (it == val.m_value.object->end())
12603 JSON_THROW(std::invalid_argument(error_msg + " must have member '" + member + "'"));
12606 // check if result is of type string
12607 if (string_type and not it->second.is_string())
12609 JSON_THROW(std::invalid_argument(error_msg + " must have string member '" + member + "'"));
12612 // no error: return value
12617 if (not val.is_object())
12619 JSON_THROW(std::invalid_argument("JSON patch must be an array of objects"));
12622 // collect mandatory members
12623 const std::string op = get_value("op", "op", true);
12624 const std::string path = get_value(op, "path", true);
12625 json_pointer ptr(path);
12627 switch (get_op(op))
12629 case patch_operations::add:
12631 operation_add(ptr, get_value("add", "value", false));
12635 case patch_operations::remove:
12637 operation_remove(ptr);
12641 case patch_operations::replace:
12643 // the "path" location must exist - use at()
12644 result.at(ptr) = get_value("replace", "value", false);
12648 case patch_operations::move:
12650 const std::string from_path = get_value("move", "from", true);
12651 json_pointer from_ptr(from_path);
12653 // the "from" location must exist - use at()
12654 basic_json v = result.at(from_ptr);
12656 // The move operation is functionally identical to a
12657 // "remove" operation on the "from" location, followed
12658 // immediately by an "add" operation at the target
12659 // location with the value that was just removed.
12660 operation_remove(from_ptr);
12661 operation_add(ptr, v);
12665 case patch_operations::copy:
12667 const std::string from_path = get_value("copy", "from", true);;
12668 const json_pointer from_ptr(from_path);
12670 // the "from" location must exist - use at()
12671 result[ptr] = result.at(from_ptr);
12675 case patch_operations::test:
12677 bool success = false;
12680 // check if "value" matches the one at "path"
12681 // the "path" location must exist - use at()
12682 success = (result.at(ptr) == get_value("test", "value", false));
12684 JSON_CATCH (std::out_of_range&)
12686 // ignore out of range errors: success remains false
12689 // throw an exception if test fails
12692 JSON_THROW(std::domain_error("unsuccessful: " + val.dump()));
12698 case patch_operations::invalid:
12700 // op must be "add", "remove", "replace", "move", "copy", or
12702 JSON_THROW(std::invalid_argument("operation value '" + op + "' is invalid"));
12711 @brief creates a diff as a JSON patch
12713 Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
12714 be changed into the value @a target by calling @ref patch function.
12716 @invariant For two JSON values @a source and @a target, the following code
12717 yields always `true`:
12719 source.patch(diff(source, target)) == target;
12722 @note Currently, only `remove`, `add`, and `replace` operations are
12725 @param[in] source JSON value to compare from
12726 @param[in] target JSON value to compare against
12727 @param[in] path helper value to create JSON pointers
12729 @return a JSON patch to convert the @a source to @a target
12731 @complexity Linear in the lengths of @a source and @a target.
12733 @liveexample{The following code shows how a JSON patch is created as a
12734 diff for two JSON values.,diff}
12736 @sa @ref patch -- apply a JSON patch
12738 @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
12740 @since version 2.0.0
12742 static basic_json diff(const basic_json& source,
12743 const basic_json& target,
12744 const std::string& path = "")
12747 basic_json result(value_t::array);
12749 // if the values are the same, return empty patch
12750 if (source == target)
12755 if (source.type() != target.type())
12757 // different types: replace value
12767 switch (source.type())
12769 case value_t::array:
12771 // first pass: traverse common elements
12773 while (i < source.size() and i < target.size())
12775 // recursive call to compare array values at index i
12776 auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
12777 result.insert(result.end(), temp_diff.begin(), temp_diff.end());
12781 // i now reached the end of at least one array
12782 // in a second pass, traverse the remaining elements
12784 // remove my remaining elements
12785 const auto end_index = static_cast<difference_type>(result.size());
12786 while (i < source.size())
12788 // add operations in reverse order to avoid invalid
12790 result.insert(result.begin() + end_index, object(
12793 {"path", path + "/" + std::to_string(i)}
12798 // add other remaining elements
12799 while (i < target.size())
12804 {"path", path + "/" + std::to_string(i)},
12805 {"value", target[i]}
12813 case value_t::object:
12815 // first pass: traverse this object's elements
12816 for (auto it = source.begin(); it != source.end(); ++it)
12818 // escape the key name to be used in a JSON patch
12819 const auto key = json_pointer::escape(it.key());
12821 if (target.find(it.key()) != target.end())
12823 // recursive call to compare object values at key it
12824 auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
12825 result.insert(result.end(), temp_diff.begin(), temp_diff.end());
12829 // found a key that is not in o -> remove it
12830 result.push_back(object(
12833 {"path", path + "/" + key}
12838 // second pass: traverse other object's elements
12839 for (auto it = target.begin(); it != target.end(); ++it)
12841 if (source.find(it.key()) == source.end())
12843 // found a key that is not in this -> add it
12844 const auto key = json_pointer::escape(it.key());
12848 {"path", path + "/" + key},
12849 {"value", it.value()}
12859 // both primitive type: replace value
12882 @brief default JSON class
12884 This type is the default specialization of the @ref basic_json class which
12885 uses the standard template types.
12887 @since version 1.0.0
12889 using json = basic_json<>;
12890 } // namespace nlohmann
12893 ///////////////////////
12894 // nonmember support //
12895 ///////////////////////
12897 // specialization of std::swap, and std::hash
12901 @brief exchanges the values of two JSON objects
12903 @since version 1.0.0
12906 inline void swap(nlohmann::json& j1,
12907 nlohmann::json& j2) noexcept(
12908 is_nothrow_move_constructible<nlohmann::json>::value and
12909 is_nothrow_move_assignable<nlohmann::json>::value
12915 /// hash value for JSON objects
12917 struct hash<nlohmann::json>
12920 @brief return a hash value for a JSON object
12922 @since version 1.0.0
12924 std::size_t operator()(const nlohmann::json& j) const
12926 // a naive hashing via the string representation
12927 const auto& h = hash<nlohmann::json::string_t>();
12928 return h(j.dump());
12934 @brief user-defined string literal for JSON values
12936 This operator implements a user-defined string literal for JSON objects. It
12937 can be used by adding `"_json"` to a string literal and returns a JSON object
12938 if no parse error occurred.
12940 @param[in] s a string representation of a JSON object
12941 @param[in] n the length of string @a s
12942 @return a JSON object
12944 @since version 1.0.0
12946 inline nlohmann::json operator "" _json(const char* s, std::size_t n)
12948 return nlohmann::json::parse(s, s + n);
12952 @brief user-defined string literal for JSON pointer
12954 This operator implements a user-defined string literal for JSON Pointers. It
12955 can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
12956 object if no parse error occurred.
12958 @param[in] s a string representation of a JSON Pointer
12959 @param[in] n the length of string @a s
12960 @return a JSON pointer object
12962 @since version 2.0.0
12964 inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
12966 return nlohmann::json::json_pointer(std::string(s, n));
12971 #undef JSON_DEPRECATED