1 /*
2 __ _____ _____ _____
3 __| | __| | | | JSON for Modern C++
4 | | |__ | | | | | | version 3.7.3
5 |_____|_____|_____|_|___| https://github.com/nlohmann/json
6
7 Licensed under the MIT License <http://opensource.org/licenses/MIT>.
8 SPDX-License-Identifier: MIT
9 Copyright (c) 2013-2019 Niels Lohmann <http://nlohmann.me>.
10
11 Permission is hereby granted, free of charge, to any person obtaining a copy
12 of this software and associated documentation files (the "Software"), to deal
13 in the Software without restriction, including without limitation the rights
14 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 copies of the Software, and to permit persons to whom the Software is
16 furnished to do so, subject to the following conditions:
17
18 The above copyright notice and this permission notice shall be included in all
19 copies or substantial portions of the Software.
20
21 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27 SOFTWARE.
28 */
29
30 #ifndef INCLUDE_NLOHMANN_JSON_HPP_
31 #define INCLUDE_NLOHMANN_JSON_HPP_
32
33 #define NLOHMANN_JSON_VERSION_MAJOR 3
34 #define NLOHMANN_JSON_VERSION_MINOR 7
35 #define NLOHMANN_JSON_VERSION_PATCH 3
36
37 #include <algorithm> // all_of, find, for_each
38 #include <cassert> // assert
39 #include <ciso646> // and, not, or
40 #include <cstddef> // nullptr_t, ptrdiff_t, size_t
41 #include <functional> // hash, less
42 #include <initializer_list> // initializer_list
43 #include <iosfwd> // istream, ostream
44 #include <iterator> // random_access_iterator_tag
45 #include <memory> // unique_ptr
46 #include <numeric> // accumulate
47 #include <string> // string, stoi, to_string
48 #include <utility> // declval, forward, move, pair, swap
49 #include <vector> // vector
50
51 #include <nlohmann/adl_serializer.hpp>
52 #include <nlohmann/detail/conversions/from_json.hpp>
53 #include <nlohmann/detail/conversions/to_json.hpp>
54 #include <nlohmann/detail/exceptions.hpp>
55 #include <nlohmann/detail/input/binary_reader.hpp>
56 #include <nlohmann/detail/input/input_adapters.hpp>
57 #include <nlohmann/detail/input/lexer.hpp>
58 #include <nlohmann/detail/input/parser.hpp>
59 #include <nlohmann/detail/iterators/internal_iterator.hpp>
60 #include <nlohmann/detail/iterators/iter_impl.hpp>
61 #include <nlohmann/detail/iterators/iteration_proxy.hpp>
62 #include <nlohmann/detail/iterators/json_reverse_iterator.hpp>
63 #include <nlohmann/detail/iterators/primitive_iterator.hpp>
operator <(const value_t lhs,const value_t rhs)64 #include <nlohmann/detail/json_pointer.hpp>
65 #include <nlohmann/detail/json_ref.hpp>
66 #include <nlohmann/detail/macro_scope.hpp>
67 #include <nlohmann/detail/meta/cpp_future.hpp>
68 #include <nlohmann/detail/meta/type_traits.hpp>
69 #include <nlohmann/detail/output/binary_writer.hpp>
70 #include <nlohmann/detail/output/output_adapters.hpp>
71 #include <nlohmann/detail/output/serializer.hpp>
72 #include <nlohmann/detail/value_t.hpp>
73 #include <nlohmann/json_fwd.hpp>
74
75 /*!
76 @brief namespace for Niels Lohmann
77 @see https://github.com/nlohmann
78 @since version 1.0.0
79 */
80 namespace nlohmann
81 {
82
83 /*!
84 @brief a class to store JSON values
85
86 @tparam ObjectType type for JSON objects (`std::map` by default; will be used
87 in @ref object_t)
88 @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used
89 in @ref array_t)
90 @tparam StringType type for JSON strings and object keys (`std::string` by
91 default; will be used in @ref string_t)
92 @tparam BooleanType type for JSON booleans (`bool` by default; will be used
93 in @ref boolean_t)
94 @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by
95 default; will be used in @ref number_integer_t)
96 @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c
97 `uint64_t` by default; will be used in @ref number_unsigned_t)
98 @tparam NumberFloatType type for JSON floating-point numbers (`double` by
99 default; will be used in @ref number_float_t)
100 @tparam AllocatorType type of the allocator to use (`std::allocator` by
101 default)
102 @tparam JSONSerializer the serializer to resolve internal calls to `to_json()`
103 and `from_json()` (@ref adl_serializer by default)
104
105 @requirement The class satisfies the following concept requirements:
106 - Basic
107 - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible):
108 JSON values can be default constructed. The result will be a JSON null
109 value.
110 - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible):
111 A JSON value can be constructed from an rvalue argument.
112 - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible):
113 A JSON value can be copy-constructed from an lvalue expression.
114 - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable):
115 A JSON value van be assigned from an rvalue argument.
116 - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable):
117 A JSON value can be copy-assigned from an lvalue expression.
118 - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible):
119 JSON values can be destructed.
120 - Layout
121 - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType):
122 JSON values have
123 [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
124 All non-static data members are private and standard layout types, the
125 class has no virtual functions or (virtual) base classes.
126 - Library-wide
127 - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable):
128 JSON values can be compared with `==`, see @ref
129 operator==(const_reference,const_reference).
130 - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable):
131 JSON values can be compared with `<`, see @ref
132 operator<(const_reference,const_reference).
133 - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable):
134 Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
135 other compatible types, using unqualified function call @ref swap().
136 - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer):
137 JSON values can be compared against `std::nullptr_t` objects which are used
138 to model the `null` value.
139 - Container
140 - [Container](https://en.cppreference.com/w/cpp/named_req/Container):
141 JSON values can be used like STL containers and provide iterator access.
142 - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer);
143 JSON values can be used like STL containers and provide reverse iterator
144 access.
145
146 @invariant The member variables @a m_value and @a m_type have the following
147 relationship:
148 - If `m_type == value_t::object`, then `m_value.object != nullptr`.
149 - If `m_type == value_t::array`, then `m_value.array != nullptr`.
150 - If `m_type == value_t::string`, then `m_value.string != nullptr`.
151 The invariants are checked by member function assert_invariant().
152
153 @internal
154 @note ObjectType trick from http://stackoverflow.com/a/9860911
155 @endinternal
156
157 @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange
158 Format](http://rfc7159.net/rfc7159)
159
160 @since version 1.0.0
161
162 @nosubgrouping
163 */
164 NLOHMANN_BASIC_JSON_TPL_DECLARATION
165 class basic_json
166 {
167 private:
168 template<detail::value_t> friend struct detail::external_constructor;
169 friend ::nlohmann::json_pointer<basic_json>;
170 friend ::nlohmann::detail::parser<basic_json>;
171 friend ::nlohmann::detail::serializer<basic_json>;
172 template<typename BasicJsonType>
173 friend class ::nlohmann::detail::iter_impl;
174 template<typename BasicJsonType, typename CharType>
175 friend class ::nlohmann::detail::binary_writer;
176 template<typename BasicJsonType, typename SAX>
177 friend class ::nlohmann::detail::binary_reader;
178 template<typename BasicJsonType>
179 friend class ::nlohmann::detail::json_sax_dom_parser;
180 template<typename BasicJsonType>
181 friend class ::nlohmann::detail::json_sax_dom_callback_parser;
182
183 /// workaround type for MSVC
184 using basic_json_t = NLOHMANN_BASIC_JSON_TPL;
185
186 // convenience aliases for types residing in namespace detail;
187 using lexer = ::nlohmann::detail::lexer<basic_json>;
188 using parser = ::nlohmann::detail::parser<basic_json>;
189
190 using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t;
191 template<typename BasicJsonType>
192 using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>;
193 template<typename BasicJsonType>
194 using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>;
195 template<typename Iterator>
196 using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>;
197 template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>;
198
199 template<typename CharType>
200 using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>;
201
202 using binary_reader = ::nlohmann::detail::binary_reader<basic_json>;
203 template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>;
204
205 using serializer = ::nlohmann::detail::serializer<basic_json>;
206
207 public:
208 using value_t = detail::value_t;
209 /// JSON Pointer, see @ref nlohmann::json_pointer
210 using json_pointer = ::nlohmann::json_pointer<basic_json>;
211 template<typename T, typename SFINAE>
212 using json_serializer = JSONSerializer<T, SFINAE>;
213 /// how to treat decoding errors
214 using error_handler_t = detail::error_handler_t;
215 /// helper type for initializer lists of basic_json values
216 using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>;
217
218 using input_format_t = detail::input_format_t;
219 /// SAX interface type, see @ref nlohmann::json_sax
220 using json_sax_t = json_sax<basic_json>;
221
222 ////////////////
223 // exceptions //
224 ////////////////
225
226 /// @name exceptions
227 /// Classes to implement user-defined exceptions.
228 /// @{
229
230 /// @copydoc detail::exception
231 using exception = detail::exception;
232 /// @copydoc detail::parse_error
233 using parse_error = detail::parse_error;
234 /// @copydoc detail::invalid_iterator
235 using invalid_iterator = detail::invalid_iterator;
236 /// @copydoc detail::type_error
237 using type_error = detail::type_error;
238 /// @copydoc detail::out_of_range
239 using out_of_range = detail::out_of_range;
240 /// @copydoc detail::other_error
241 using other_error = detail::other_error;
242
243 /// @}
244
245
246 /////////////////////
247 // container types //
248 /////////////////////
249
250 /// @name container types
251 /// The canonic container types to use @ref basic_json like any other STL
252 /// container.
253 /// @{
254
255 /// the type of elements in a basic_json container
256 using value_type = basic_json;
257
258 /// the type of an element reference
259 using reference = value_type&;
260 /// the type of an element const reference
261 using const_reference = const value_type&;
262
263 /// a type to represent differences between iterators
264 using difference_type = std::ptrdiff_t;
265 /// a type to represent container sizes
266 using size_type = std::size_t;
267
268 /// the allocator type
269 using allocator_type = AllocatorType<basic_json>;
270
271 /// the type of an element pointer
272 using pointer = typename std::allocator_traits<allocator_type>::pointer;
273 /// the type of an element const pointer
274 using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
275
276 /// an iterator for a basic_json container
277 using iterator = iter_impl<basic_json>;
278 /// a const iterator for a basic_json container
279 using const_iterator = iter_impl<const basic_json>;
280 /// a reverse iterator for a basic_json container
281 using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
282 /// a const reverse iterator for a basic_json container
283 using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
284
285 /// @}
286
287
288 /*!
289 @brief returns the allocator associated with the container
290 */
291 static allocator_type get_allocator()
292 {
293 return allocator_type();
294 }
295
296 /*!
297 @brief returns version information on the library
298
299 This function returns a JSON object with information about the library,
300 including the version number and information on the platform and compiler.
301
302 @return JSON object holding version information
303 key | description
304 ----------- | ---------------
305 `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).
306 `copyright` | The copyright line for the library as string.
307 `name` | The name of the library as string.
308 `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`.
309 `url` | The URL of the project as string.
310 `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).
311
312 @liveexample{The following code shows an example output of the `meta()`
313 function.,meta}
314
315 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
316 changes to any JSON value.
317
318 @complexity Constant.
319
320 @since 2.1.0
321 */
322 JSON_HEDLEY_WARN_UNUSED_RESULT
323 static basic_json meta()
324 {
325 basic_json result;
326
327 result["copyright"] = "(C) 2013-2017 Niels Lohmann";
328 result["name"] = "JSON for Modern C++";
329 result["url"] = "https://github.com/nlohmann/json";
330 result["version"]["string"] =
331 std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." +
332 std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." +
333 std::to_string(NLOHMANN_JSON_VERSION_PATCH);
334 result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR;
335 result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR;
336 result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH;
337
338 #ifdef _WIN32
339 result["platform"] = "win32";
340 #elif defined __linux__
341 result["platform"] = "linux";
342 #elif defined __APPLE__
343 result["platform"] = "apple";
344 #elif defined __unix__
345 result["platform"] = "unix";
346 #else
347 result["platform"] = "unknown";
348 #endif
349
350 #if defined(__ICC) || defined(__INTEL_COMPILER)
351 result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}};
352 #elif defined(__clang__)
353 result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}};
354 #elif defined(__GNUC__) || defined(__GNUG__)
355 result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}};
356 #elif defined(__HP_cc) || defined(__HP_aCC)
357 result["compiler"] = "hp"
358 #elif defined(__IBMCPP__)
359 result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}};
360 #elif defined(_MSC_VER)
361 result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}};
362 #elif defined(__PGI)
363 result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}};
364 #elif defined(__SUNPRO_CC)
365 result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}};
366 #else
367 result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}};
368 #endif
369
370 #ifdef __cplusplus
371 result["compiler"]["c++"] = std::to_string(__cplusplus);
372 #else
373 result["compiler"]["c++"] = "unknown";
374 #endif
375 return result;
376 }
377
378
379 ///////////////////////////
380 // JSON value data types //
381 ///////////////////////////
382
383 /// @name JSON value data types
384 /// The data types to store a JSON value. These types are derived from
385 /// the template arguments passed to class @ref basic_json.
386 /// @{
387
388 #if defined(JSON_HAS_CPP_14)
389 // Use transparent comparator if possible, combined with perfect forwarding
390 // on find() and count() calls prevents unnecessary string construction.
391 using object_comparator_t = std::less<>;
392 #else
393 using object_comparator_t = std::less<StringType>;
394 #endif
395
396 /*!
397 @brief a type for an object
398
399 [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
400 > An object is an unordered collection of zero or more name/value pairs,
401 > where a name is a string and a value is a string, number, boolean, null,
402 > object, or array.
403
404 To store objects in C++, a type is defined by the template parameters
405 described below.
406
407 @tparam ObjectType the container to store objects (e.g., `std::map` or
408 `std::unordered_map`)
409 @tparam StringType the type of the keys or names (e.g., `std::string`).
410 The comparison function `std::less<StringType>` is used to order elements
411 inside the container.
412 @tparam AllocatorType the allocator to use for objects (e.g.,
413 `std::allocator`)
414
415 #### Default type
416
417 With the default values for @a ObjectType (`std::map`), @a StringType
418 (`std::string`), and @a AllocatorType (`std::allocator`), the default
419 value for @a object_t is:
420
421 @code {.cpp}
422 std::map<
423 std::string, // key_type
424 basic_json, // value_type
425 std::less<std::string>, // key_compare
426 std::allocator<std::pair<const std::string, basic_json>> // allocator_type
427 >
428 @endcode
429
430 #### Behavior
431
432 The choice of @a object_t influences the behavior of the JSON class. With
433 the default type, objects have the following behavior:
434
435 - When all names are unique, objects will be interoperable in the sense
436 that all software implementations receiving that object will agree on
437 the name-value mappings.
438 - When the names within an object are not unique, it is unspecified which
439 one of the values for a given key will be chosen. For instance,
440 `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or
441 `{"key": 2}`.
442 - Internally, name/value pairs are stored in lexicographical order of the
443 names. Objects will also be serialized (see @ref dump) in this order.
444 For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored
445 and serialized as `{"a": 2, "b": 1}`.
446 - When comparing objects, the order of the name/value pairs is irrelevant.
447 This makes objects interoperable in the sense that they will not be
448 affected by these differences. For instance, `{"b": 1, "a": 2}` and
449 `{"a": 2, "b": 1}` will be treated as equal.
450
451 #### Limits
452
453 [RFC 7159](http://rfc7159.net/rfc7159) specifies:
454 > An implementation may set limits on the maximum depth of nesting.
455
456 In this class, the object's limit of nesting is not explicitly constrained.
457 However, a maximum depth of nesting may be introduced by the compiler or
458 runtime environment. A theoretical limit can be queried by calling the
459 @ref max_size function of a JSON object.
460
461 #### Storage
462
463 Objects are stored as pointers in a @ref basic_json type. That is, for any
464 access to object values, a pointer of type `object_t*` must be
465 dereferenced.
466
467 @sa @ref array_t -- type for an array value
468
469 @since version 1.0.0
470
471 @note The order name/value pairs are added to the object is *not*
472 preserved by the library. Therefore, iterating an object may return
473 name/value pairs in a different order than they were originally stored. In
474 fact, keys will be traversed in alphabetical order as `std::map` with
475 `std::less` is used by default. Please note this behavior conforms to [RFC
476 7159](http://rfc7159.net/rfc7159), because any order implements the
477 specified "unordered" nature of JSON objects.
478 */
479 using object_t = ObjectType<StringType,
480 basic_json,
481 object_comparator_t,
482 AllocatorType<std::pair<const StringType,
483 basic_json>>>;
484
485 /*!
486 @brief a type for an array
487
488 [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
489 > An array is an ordered sequence of zero or more values.
490
491 To store objects in C++, a type is defined by the template parameters
492 explained below.
493
494 @tparam ArrayType container type to store arrays (e.g., `std::vector` or
495 `std::list`)
496 @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
497
498 #### Default type
499
500 With the default values for @a ArrayType (`std::vector`) and @a
501 AllocatorType (`std::allocator`), the default value for @a array_t is:
502
503 @code {.cpp}
504 std::vector<
505 basic_json, // value_type
506 std::allocator<basic_json> // allocator_type
507 >
508 @endcode
509
510 #### Limits
511
512 [RFC 7159](http://rfc7159.net/rfc7159) specifies:
513 > An implementation may set limits on the maximum depth of nesting.
514
515 In this class, the array's limit of nesting is not explicitly constrained.
516 However, a maximum depth of nesting may be introduced by the compiler or
517 runtime environment. A theoretical limit can be queried by calling the
518 @ref max_size function of a JSON array.
519
520 #### Storage
521
522 Arrays are stored as pointers in a @ref basic_json type. That is, for any
523 access to array values, a pointer of type `array_t*` must be dereferenced.
524
525 @sa @ref object_t -- type for an object value
526
527 @since version 1.0.0
528 */
529 using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
530
531 /*!
532 @brief a type for a string
533
534 [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
535 > A string is a sequence of zero or more Unicode characters.
536
537 To store objects in C++, a type is defined by the template parameter
538 described below. Unicode values are split by the JSON class into
539 byte-sized characters during deserialization.
540
541 @tparam StringType the container to store strings (e.g., `std::string`).
542 Note this container is used for keys/names in objects, see @ref object_t.
543
544 #### Default type
545
546 With the default values for @a StringType (`std::string`), the default
547 value for @a string_t is:
548
549 @code {.cpp}
550 std::string
551 @endcode
552
553 #### Encoding
554
555 Strings are stored in UTF-8 encoding. Therefore, functions like
556 `std::string::size()` or `std::string::length()` return the number of
557 bytes in the string rather than the number of characters or glyphs.
558
559 #### String comparison
560
561 [RFC 7159](http://rfc7159.net/rfc7159) states:
562 > Software implementations are typically required to test names of object
563 > members for equality. Implementations that transform the textual
564 > representation into sequences of Unicode code units and then perform the
565 > comparison numerically, code unit by code unit, are interoperable in the
566 > sense that implementations will agree in all cases on equality or
567 > inequality of two strings. For example, implementations that compare
568 > strings with escaped characters unconverted may incorrectly find that
569 > `"a\\b"` and `"a\u005Cb"` are not equal.
570
571 This implementation is interoperable as it does compare strings code unit
572 by code unit.
573
574 #### Storage
575
576 String values are stored as pointers in a @ref basic_json type. That is,
577 for any access to string values, a pointer of type `string_t*` must be
578 dereferenced.
579
580 @since version 1.0.0
581 */
582 using string_t = StringType;
583
584 /*!
585 @brief a type for a boolean
586
587 [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
588 type which differentiates the two literals `true` and `false`.
589
590 To store objects in C++, a type is defined by the template parameter @a
591 BooleanType which chooses the type to use.
592
593 #### Default type
594
595 With the default values for @a BooleanType (`bool`), the default value for
596 @a boolean_t is:
597
598 @code {.cpp}
599 bool
600 @endcode
601
602 #### Storage
603
604 Boolean values are stored directly inside a @ref basic_json type.
605
606 @since version 1.0.0
607 */
608 using boolean_t = BooleanType;
609
610 /*!
611 @brief a type for a number (integer)
612
613 [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
614 > The representation of numbers is similar to that used in most
615 > programming languages. A number is represented in base 10 using decimal
616 > digits. It contains an integer component that may be prefixed with an
617 > optional minus sign, which may be followed by a fraction part and/or an
618 > exponent part. Leading zeros are not allowed. (...) Numeric values that
619 > cannot be represented in the grammar below (such as Infinity and NaN)
620 > are not permitted.
621
622 This description includes both integer and floating-point numbers.
623 However, C++ allows more precise storage if it is known whether the number
624 is a signed integer, an unsigned integer or a floating-point number.
625 Therefore, three different types, @ref number_integer_t, @ref
626 number_unsigned_t and @ref number_float_t are used.
627
628 To store integer numbers in C++, a type is defined by the template
629 parameter @a NumberIntegerType which chooses the type to use.
630
631 #### Default type
632
633 With the default values for @a NumberIntegerType (`int64_t`), the default
634 value for @a number_integer_t is:
635
636 @code {.cpp}
637 int64_t
638 @endcode
639
640 #### Default behavior
641
642 - The restrictions about leading zeros is not enforced in C++. Instead,
643 leading zeros in integer literals lead to an interpretation as octal
644 number. Internally, the value will be stored as decimal number. For
645 instance, the C++ integer literal `010` will be serialized to `8`.
646 During deserialization, leading zeros yield an error.
647 - Not-a-number (NaN) values will be serialized to `null`.
648
649 #### Limits
650
651 [RFC 7159](http://rfc7159.net/rfc7159) specifies:
652 > An implementation may set limits on the range and precision of numbers.
653
654 When the default type is used, the maximal integer number that can be
655 stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
656 that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
657 that are out of range will yield over/underflow when used in a
658 constructor. During deserialization, too large or small integer numbers
659 will be automatically be stored as @ref number_unsigned_t or @ref
660 number_float_t.
661
662 [RFC 7159](http://rfc7159.net/rfc7159) further states:
663 > Note that when such software is used, numbers that are integers and are
664 > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
665 > that implementations will agree exactly on their numeric values.
666
667 As this range is a subrange of the exactly supported range [INT64_MIN,
668 INT64_MAX], this class's integer type is interoperable.
669
670 #### Storage
671
672 Integer number values are stored directly inside a @ref basic_json type.
673
674 @sa @ref number_float_t -- type for number values (floating-point)
675
676 @sa @ref number_unsigned_t -- type for number values (unsigned integer)
677
678 @since version 1.0.0
679 */
680 using number_integer_t = NumberIntegerType;
681
682 /*!
683 @brief a type for a number (unsigned)
684
685 [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
686 > The representation of numbers is similar to that used in most
687 > programming languages. A number is represented in base 10 using decimal
688 > digits. It contains an integer component that may be prefixed with an
689 > optional minus sign, which may be followed by a fraction part and/or an
690 > exponent part. Leading zeros are not allowed. (...) Numeric values that
691 > cannot be represented in the grammar below (such as Infinity and NaN)
692 > are not permitted.
693
694 This description includes both integer and floating-point numbers.
695 However, C++ allows more precise storage if it is known whether the number
696 is a signed integer, an unsigned integer or a floating-point number.
697 Therefore, three different types, @ref number_integer_t, @ref
698 number_unsigned_t and @ref number_float_t are used.
699
700 To store unsigned integer numbers in C++, a type is defined by the
701 template parameter @a NumberUnsignedType which chooses the type to use.
702
703 #### Default type
704
705 With the default values for @a NumberUnsignedType (`uint64_t`), the
706 default value for @a number_unsigned_t is:
707
708 @code {.cpp}
709 uint64_t
710 @endcode
711
712 #### Default behavior
713
714 - The restrictions about leading zeros is not enforced in C++. Instead,
715 leading zeros in integer literals lead to an interpretation as octal
716 number. Internally, the value will be stored as decimal number. For
717 instance, the C++ integer literal `010` will be serialized to `8`.
718 During deserialization, leading zeros yield an error.
719 - Not-a-number (NaN) values will be serialized to `null`.
720
721 #### Limits
722
723 [RFC 7159](http://rfc7159.net/rfc7159) specifies:
724 > An implementation may set limits on the range and precision of numbers.
725
726 When the default type is used, the maximal integer number that can be
727 stored is `18446744073709551615` (UINT64_MAX) and the minimal integer
728 number that can be stored is `0`. Integer numbers that are out of range
729 will yield over/underflow when used in a constructor. During
730 deserialization, too large or small integer numbers will be automatically
731 be stored as @ref number_integer_t or @ref number_float_t.
732
733 [RFC 7159](http://rfc7159.net/rfc7159) further states:
734 > Note that when such software is used, numbers that are integers and are
735 > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
736 > that implementations will agree exactly on their numeric values.
737
738 As this range is a subrange (when considered in conjunction with the
739 number_integer_t type) of the exactly supported range [0, UINT64_MAX],
740 this class's integer type is interoperable.
741
742 #### Storage
743
744 Integer number values are stored directly inside a @ref basic_json type.
745
746 @sa @ref number_float_t -- type for number values (floating-point)
747 @sa @ref number_integer_t -- type for number values (integer)
748
749 @since version 2.0.0
750 */
751 using number_unsigned_t = NumberUnsignedType;
752
753 /*!
754 @brief a type for a number (floating-point)
755
756 [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
757 > The representation of numbers is similar to that used in most
758 > programming languages. A number is represented in base 10 using decimal
759 > digits. It contains an integer component that may be prefixed with an
760 > optional minus sign, which may be followed by a fraction part and/or an
761 > exponent part. Leading zeros are not allowed. (...) Numeric values that
762 > cannot be represented in the grammar below (such as Infinity and NaN)
763 > are not permitted.
764
765 This description includes both integer and floating-point numbers.
766 However, C++ allows more precise storage if it is known whether the number
767 is a signed integer, an unsigned integer or a floating-point number.
768 Therefore, three different types, @ref number_integer_t, @ref
769 number_unsigned_t and @ref number_float_t are used.
770
771 To store floating-point numbers in C++, a type is defined by the template
772 parameter @a NumberFloatType which chooses the type to use.
773
774 #### Default type
775
776 With the default values for @a NumberFloatType (`double`), the default
777 value for @a number_float_t is:
778
779 @code {.cpp}
780 double
781 @endcode
782
783 #### Default behavior
784
785 - The restrictions about leading zeros is not enforced in C++. Instead,
786 leading zeros in floating-point literals will be ignored. Internally,
787 the value will be stored as decimal number. For instance, the C++
788 floating-point literal `01.2` will be serialized to `1.2`. During
789 deserialization, leading zeros yield an error.
790 - Not-a-number (NaN) values will be serialized to `null`.
791
792 #### Limits
793
794 [RFC 7159](http://rfc7159.net/rfc7159) states:
795 > This specification allows implementations to set limits on the range and
796 > precision of numbers accepted. Since software that implements IEEE
797 > 754-2008 binary64 (double precision) numbers is generally available and
798 > widely used, good interoperability can be achieved by implementations
799 > that expect no more precision or range than these provide, in the sense
800 > that implementations will approximate JSON numbers within the expected
801 > precision.
802
803 This implementation does exactly follow this approach, as it uses double
804 precision floating-point numbers. Note values smaller than
805 `-1.79769313486232e+308` and values greater than `1.79769313486232e+308`
806 will be stored as NaN internally and be serialized to `null`.
807
808 #### Storage
809
810 Floating-point number values are stored directly inside a @ref basic_json
811 type.
812
813 @sa @ref number_integer_t -- type for number values (integer)
814
815 @sa @ref number_unsigned_t -- type for number values (unsigned integer)
816
817 @since version 1.0.0
818 */
819 using number_float_t = NumberFloatType;
820
821 /// @}
822
823 private:
824
825 /// helper for exception-safe object creation
826 template<typename T, typename... Args>
827 JSON_HEDLEY_RETURNS_NON_NULL
828 static T* create(Args&& ... args)
829 {
830 AllocatorType<T> alloc;
831 using AllocatorTraits = std::allocator_traits<AllocatorType<T>>;
832
833 auto deleter = [&](T * object)
834 {
835 AllocatorTraits::deallocate(alloc, object, 1);
836 };
837 std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter);
838 AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...);
839 assert(object != nullptr);
840 return object.release();
841 }
842
843 ////////////////////////
844 // JSON value storage //
845 ////////////////////////
846
847 /*!
848 @brief a JSON value
849
850 The actual storage for a JSON value of the @ref basic_json class. This
851 union combines the different storage types for the JSON value types
852 defined in @ref value_t.
853
854 JSON type | value_t type | used type
855 --------- | --------------- | ------------------------
856 object | object | pointer to @ref object_t
857 array | array | pointer to @ref array_t
858 string | string | pointer to @ref string_t
859 boolean | boolean | @ref boolean_t
860 number | number_integer | @ref number_integer_t
861 number | number_unsigned | @ref number_unsigned_t
862 number | number_float | @ref number_float_t
863 null | null | *no value is stored*
864
865 @note Variable-length types (objects, arrays, and strings) are stored as
866 pointers. The size of the union should not exceed 64 bits if the default
867 value types are used.
868
869 @since version 1.0.0
870 */
871 union json_value
872 {
873 /// object (stored with pointer to save storage)
874 object_t* object;
875 /// array (stored with pointer to save storage)
876 array_t* array;
877 /// string (stored with pointer to save storage)
878 string_t* string;
879 /// boolean
880 boolean_t boolean;
881 /// number (integer)
882 number_integer_t number_integer;
883 /// number (unsigned integer)
884 number_unsigned_t number_unsigned;
885 /// number (floating-point)
886 number_float_t number_float;
887
888 /// default constructor (for null values)
889 json_value() = default;
890 /// constructor for booleans
891 json_value(boolean_t v) noexcept : boolean(v) {}
892 /// constructor for numbers (integer)
893 json_value(number_integer_t v) noexcept : number_integer(v) {}
894 /// constructor for numbers (unsigned)
895 json_value(number_unsigned_t v) noexcept : number_unsigned(v) {}
896 /// constructor for numbers (floating-point)
897 json_value(number_float_t v) noexcept : number_float(v) {}
898 /// constructor for empty values of a given type
899 json_value(value_t t)
900 {
901 switch (t)
902 {
903 case value_t::object:
904 {
905 object = create<object_t>();
906 break;
907 }
908
909 case value_t::array:
910 {
911 array = create<array_t>();
912 break;
913 }
914
915 case value_t::string:
916 {
917 string = create<string_t>("");
918 break;
919 }
920
921 case value_t::boolean:
922 {
923 boolean = boolean_t(false);
924 break;
925 }
926
927 case value_t::number_integer:
928 {
929 number_integer = number_integer_t(0);
930 break;
931 }
932
933 case value_t::number_unsigned:
934 {
935 number_unsigned = number_unsigned_t(0);
936 break;
937 }
938
939 case value_t::number_float:
940 {
941 number_float = number_float_t(0.0);
942 break;
943 }
944
945 case value_t::null:
946 {
947 object = nullptr; // silence warning, see #821
948 break;
949 }
950
951 default:
952 {
953 object = nullptr; // silence warning, see #821
954 if (JSON_HEDLEY_UNLIKELY(t == value_t::null))
955 {
956 JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.7.3")); // LCOV_EXCL_LINE
957 }
958 break;
959 }
960 }
961 }
962
963 /// constructor for strings
964 json_value(const string_t& value)
965 {
966 string = create<string_t>(value);
967 }
968
969 /// constructor for rvalue strings
970 json_value(string_t&& value)
971 {
972 string = create<string_t>(std::move(value));
973 }
974
975 /// constructor for objects
976 json_value(const object_t& value)
977 {
978 object = create<object_t>(value);
979 }
980
981 /// constructor for rvalue objects
982 json_value(object_t&& value)
983 {
984 object = create<object_t>(std::move(value));
985 }
986
987 /// constructor for arrays
988 json_value(const array_t& value)
989 {
990 array = create<array_t>(value);
991 }
992
993 /// constructor for rvalue arrays
994 json_value(array_t&& value)
995 {
996 array = create<array_t>(std::move(value));
997 }
998
999 void destroy(value_t t) noexcept
1000 {
1001 // flatten the current json_value to a heap-allocated stack
1002 std::vector<basic_json> stack;
1003
1004 // move the top-level items to stack
1005 if (t == value_t::array)
1006 {
1007 stack.reserve(array->size());
1008 std::move(array->begin(), array->end(), std::back_inserter(stack));
1009 }
1010 else if (t == value_t::object)
1011 {
1012 stack.reserve(object->size());
1013 for (auto&& it : *object)
1014 {
1015 stack.push_back(std::move(it.second));
1016 }
1017 }
1018
1019 while (not stack.empty())
1020 {
1021 // move the last item to local variable to be processed
1022 basic_json current_item(std::move(stack.back()));
1023 stack.pop_back();
1024
1025 // if current_item is array/object, move
1026 // its children to the stack to be processed later
1027 if (current_item.is_array())
1028 {
1029 std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(),
1030 std::back_inserter(stack));
1031
1032 current_item.m_value.array->clear();
1033 }
1034 else if (current_item.is_object())
1035 {
1036 for (auto&& it : *current_item.m_value.object)
1037 {
1038 stack.push_back(std::move(it.second));
1039 }
1040
1041 current_item.m_value.object->clear();
1042 }
1043
1044 // it's now safe that current_item get destructed
1045 // since it doesn't have any children
1046 }
1047
1048 switch (t)
1049 {
1050 case value_t::object:
1051 {
1052 AllocatorType<object_t> alloc;
1053 std::allocator_traits<decltype(alloc)>::destroy(alloc, object);
1054 std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1);
1055 break;
1056 }
1057
1058 case value_t::array:
1059 {
1060 AllocatorType<array_t> alloc;
1061 std::allocator_traits<decltype(alloc)>::destroy(alloc, array);
1062 std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1);
1063 break;
1064 }
1065
1066 case value_t::string:
1067 {
1068 AllocatorType<string_t> alloc;
1069 std::allocator_traits<decltype(alloc)>::destroy(alloc, string);
1070 std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1);
1071 break;
1072 }
1073
1074 default:
1075 {
1076 break;
1077 }
1078 }
1079 }
1080 };
1081
1082 /*!
1083 @brief checks the class invariants
1084
1085 This function asserts the class invariants. It needs to be called at the
1086 end of every constructor to make sure that created objects respect the
1087 invariant. Furthermore, it has to be called each time the type of a JSON
1088 value is changed, because the invariant expresses a relationship between
1089 @a m_type and @a m_value.
1090 */
1091 void assert_invariant() const noexcept
1092 {
1093 assert(m_type != value_t::object or m_value.object != nullptr);
1094 assert(m_type != value_t::array or m_value.array != nullptr);
1095 assert(m_type != value_t::string or m_value.string != nullptr);
1096 }
1097
1098 public:
1099 //////////////////////////
1100 // JSON parser callback //
1101 //////////////////////////
1102
1103 /*!
1104 @brief parser event types
1105
1106 The parser callback distinguishes the following events:
1107 - `object_start`: the parser read `{` and started to process a JSON object
1108 - `key`: the parser read a key of a value in an object
1109 - `object_end`: the parser read `}` and finished processing a JSON object
1110 - `array_start`: the parser read `[` and started to process a JSON array
1111 - `array_end`: the parser read `]` and finished processing a JSON array
1112 - `value`: the parser finished reading a JSON value
1113
1114 @image html callback_events.png "Example when certain parse events are triggered"
1115
1116 @sa @ref parser_callback_t for more information and examples
1117 */
1118 using parse_event_t = typename parser::parse_event_t;
1119
1120 /*!
1121 @brief per-element parser callback type
1122
1123 With a parser callback function, the result of parsing a JSON text can be
1124 influenced. When passed to @ref parse, it is called on certain events
1125 (passed as @ref parse_event_t via parameter @a event) with a set recursion
1126 depth @a depth and context JSON value @a parsed. The return value of the
1127 callback function is a boolean indicating whether the element that emitted
1128 the callback shall be kept or not.
1129
1130 We distinguish six scenarios (determined by the event type) in which the
1131 callback function can be called. The following table describes the values
1132 of the parameters @a depth, @a event, and @a parsed.
1133
1134 parameter @a event | description | parameter @a depth | parameter @a parsed
1135 ------------------ | ----------- | ------------------ | -------------------
1136 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
1137 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
1138 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
1139 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
1140 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
1141 parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
1142
1143 @image html callback_events.png "Example when certain parse events are triggered"
1144
1145 Discarding a value (i.e., returning `false`) has different effects
1146 depending on the context in which function was called:
1147
1148 - Discarded values in structured types are skipped. That is, the parser
1149 will behave as if the discarded value was never read.
1150 - In case a value outside a structured type is skipped, it is replaced
1151 with `null`. This case happens if the top-level element is skipped.
1152
1153 @param[in] depth the depth of the recursion during parsing
1154
1155 @param[in] event an event of type parse_event_t indicating the context in
1156 the callback function has been called
1157
1158 @param[in,out] parsed the current intermediate parse result; note that
1159 writing to this value has no effect for parse_event_t::key events
1160
1161 @return Whether the JSON value which called the function during parsing
1162 should be kept (`true`) or not (`false`). In the latter case, it is either
1163 skipped completely or replaced by an empty discarded object.
1164
1165 @sa @ref parse for examples
1166
1167 @since version 1.0.0
1168 */
1169 using parser_callback_t = typename parser::parser_callback_t;
1170
1171 //////////////////
1172 // constructors //
1173 //////////////////
1174
1175 /// @name constructors and destructors
1176 /// Constructors of class @ref basic_json, copy/move constructor, copy
1177 /// assignment, static functions creating objects, and the destructor.
1178 /// @{
1179
1180 /*!
1181 @brief create an empty value with a given type
1182
1183 Create an empty JSON value with a given type. The value will be default
1184 initialized with an empty value which depends on the type:
1185
1186 Value type | initial value
1187 ----------- | -------------
1188 null | `null`
1189 boolean | `false`
1190 string | `""`
1191 number | `0`
1192 object | `{}`
1193 array | `[]`
1194
1195 @param[in] v the type of the value to create
1196
1197 @complexity Constant.
1198
1199 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
1200 changes to any JSON value.
1201
1202 @liveexample{The following code shows the constructor for different @ref
1203 value_t values,basic_json__value_t}
1204
1205 @sa @ref clear() -- restores the postcondition of this constructor
1206
1207 @since version 1.0.0
1208 */
1209 basic_json(const value_t v)
1210 : m_type(v), m_value(v)
1211 {
1212 assert_invariant();
1213 }
1214
1215 /*!
1216 @brief create a null object
1217
1218 Create a `null` JSON value. It either takes a null pointer as parameter
1219 (explicitly creating `null`) or no parameter (implicitly creating `null`).
1220 The passed null pointer itself is not read -- it is only used to choose
1221 the right constructor.
1222
1223 @complexity Constant.
1224
1225 @exceptionsafety No-throw guarantee: this constructor never throws
1226 exceptions.
1227
1228 @liveexample{The following code shows the constructor with and without a
1229 null pointer parameter.,basic_json__nullptr_t}
1230
1231 @since version 1.0.0
1232 */
1233 basic_json(std::nullptr_t = nullptr) noexcept
1234 : basic_json(value_t::null)
1235 {
1236 assert_invariant();
1237 }
1238
1239 /*!
1240 @brief create a JSON value
1241
1242 This is a "catch all" constructor for all compatible JSON types; that is,
1243 types for which a `to_json()` method exists. The constructor forwards the
1244 parameter @a val to that method (to `json_serializer<U>::to_json` method
1245 with `U = uncvref_t<CompatibleType>`, to be exact).
1246
1247 Template type @a CompatibleType includes, but is not limited to, the
1248 following types:
1249 - **arrays**: @ref array_t and all kinds of compatible containers such as
1250 `std::vector`, `std::deque`, `std::list`, `std::forward_list`,
1251 `std::array`, `std::valarray`, `std::set`, `std::unordered_set`,
1252 `std::multiset`, and `std::unordered_multiset` with a `value_type` from
1253 which a @ref basic_json value can be constructed.
1254 - **objects**: @ref object_t and all kinds of compatible associative
1255 containers such as `std::map`, `std::unordered_map`, `std::multimap`,
1256 and `std::unordered_multimap` with a `key_type` compatible to
1257 @ref string_t and a `value_type` from which a @ref basic_json value can
1258 be constructed.
1259 - **strings**: @ref string_t, string literals, and all compatible string
1260 containers can be used.
1261 - **numbers**: @ref number_integer_t, @ref number_unsigned_t,
1262 @ref number_float_t, and all convertible number types such as `int`,
1263 `size_t`, `int64_t`, `float` or `double` can be used.
1264 - **boolean**: @ref boolean_t / `bool` can be used.
1265
1266 See the examples below.
1267
1268 @tparam CompatibleType a type such that:
1269 - @a CompatibleType is not derived from `std::istream`,
1270 - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move
1271 constructors),
1272 - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments)
1273 - @a CompatibleType is not a @ref basic_json nested type (e.g.,
1274 @ref json_pointer, @ref iterator, etc ...)
1275 - @ref @ref json_serializer<U> has a
1276 `to_json(basic_json_t&, CompatibleType&&)` method
1277
1278 @tparam U = `uncvref_t<CompatibleType>`
1279
1280 @param[in] val the value to be forwarded to the respective constructor
1281
1282 @complexity Usually linear in the size of the passed @a val, also
1283 depending on the implementation of the called `to_json()`
1284 method.
1285
1286 @exceptionsafety Depends on the called constructor. For types directly
1287 supported by the library (i.e., all types for which no `to_json()` function
1288 was provided), strong guarantee holds: if an exception is thrown, there are
1289 no changes to any JSON value.
1290
1291 @liveexample{The following code shows the constructor with several
1292 compatible types.,basic_json__CompatibleType}
1293
1294 @since version 2.1.0
1295 */
1296 template <typename CompatibleType,
1297 typename U = detail::uncvref_t<CompatibleType>,
1298 detail::enable_if_t<
1299 not detail::is_basic_json<U>::value and detail::is_compatible_type<basic_json_t, U>::value, int> = 0>
1300 basic_json(CompatibleType && val) noexcept(noexcept(
1301 JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
1302 std::forward<CompatibleType>(val))))
1303 {
1304 JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val));
1305 assert_invariant();
1306 }
1307
1308 /*!
1309 @brief create a JSON value from an existing one
1310
1311 This is a constructor for existing @ref basic_json types.
1312 It does not hijack copy/move constructors, since the parameter has different
1313 template arguments than the current ones.
1314
1315 The constructor tries to convert the internal @ref m_value of the parameter.
1316
1317 @tparam BasicJsonType a type such that:
1318 - @a BasicJsonType is a @ref basic_json type.
1319 - @a BasicJsonType has different template arguments than @ref basic_json_t.
1320
1321 @param[in] val the @ref basic_json value to be converted.
1322
1323 @complexity Usually linear in the size of the passed @a val, also
1324 depending on the implementation of the called `to_json()`
1325 method.
1326
1327 @exceptionsafety Depends on the called constructor. For types directly
1328 supported by the library (i.e., all types for which no `to_json()` function
1329 was provided), strong guarantee holds: if an exception is thrown, there are
1330 no changes to any JSON value.
1331
1332 @since version 3.2.0
1333 */
1334 template <typename BasicJsonType,
1335 detail::enable_if_t<
1336 detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0>
1337 basic_json(const BasicJsonType& val)
1338 {
1339 using other_boolean_t = typename BasicJsonType::boolean_t;
1340 using other_number_float_t = typename BasicJsonType::number_float_t;
1341 using other_number_integer_t = typename BasicJsonType::number_integer_t;
1342 using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t;
1343 using other_string_t = typename BasicJsonType::string_t;
1344 using other_object_t = typename BasicJsonType::object_t;
1345 using other_array_t = typename BasicJsonType::array_t;
1346
1347 switch (val.type())
1348 {
1349 case value_t::boolean:
1350 JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>());
1351 break;
1352 case value_t::number_float:
1353 JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>());
1354 break;
1355 case value_t::number_integer:
1356 JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>());
1357 break;
1358 case value_t::number_unsigned:
1359 JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>());
1360 break;
1361 case value_t::string:
1362 JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>());
1363 break;
1364 case value_t::object:
1365 JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>());
1366 break;
1367 case value_t::array:
1368 JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>());
1369 break;
1370 case value_t::null:
1371 *this = nullptr;
1372 break;
1373 case value_t::discarded:
1374 m_type = value_t::discarded;
1375 break;
1376 default: // LCOV_EXCL_LINE
1377 assert(false); // LCOV_EXCL_LINE
1378 }
1379 assert_invariant();
1380 }
1381
1382 /*!
1383 @brief create a container (array or object) from an initializer list
1384
1385 Creates a JSON value of type array or object from the passed initializer
1386 list @a init. In case @a type_deduction is `true` (default), the type of
1387 the JSON value to be created is deducted from the initializer list @a init
1388 according to the following rules:
1389
1390 1. If the list is empty, an empty JSON object value `{}` is created.
1391 2. If the list consists of pairs whose first element is a string, a JSON
1392 object value is created where the first elements of the pairs are
1393 treated as keys and the second elements are as values.
1394 3. In all other cases, an array is created.
1395
1396 The rules aim to create the best fit between a C++ initializer list and
1397 JSON values. The rationale is as follows:
1398
1399 1. The empty initializer list is written as `{}` which is exactly an empty
1400 JSON object.
1401 2. C++ has no way of describing mapped types other than to list a list of
1402 pairs. As JSON requires that keys must be of type string, rule 2 is the
1403 weakest constraint one can pose on initializer lists to interpret them
1404 as an object.
1405 3. In all other cases, the initializer list could not be interpreted as
1406 JSON object type, so interpreting it as JSON array type is safe.
1407
1408 With the rules described above, the following JSON values cannot be
1409 expressed by an initializer list:
1410
1411 - the empty array (`[]`): use @ref array(initializer_list_t)
1412 with an empty initializer list in this case
1413 - arrays whose elements satisfy rule 2: use @ref
1414 array(initializer_list_t) with the same initializer list
1415 in this case
1416
1417 @note When used without parentheses around an empty initializer list, @ref
1418 basic_json() is called instead of this function, yielding the JSON null
1419 value.
1420
1421 @param[in] init initializer list with JSON values
1422
1423 @param[in] type_deduction internal parameter; when set to `true`, the type
1424 of the JSON value is deducted from the initializer list @a init; when set
1425 to `false`, the type provided via @a manual_type is forced. This mode is
1426 used by the functions @ref array(initializer_list_t) and
1427 @ref object(initializer_list_t).
1428
1429 @param[in] manual_type internal parameter; when @a type_deduction is set
1430 to `false`, the created JSON value will use the provided type (only @ref
1431 value_t::array and @ref value_t::object are valid); when @a type_deduction
1432 is set to `true`, this parameter has no effect
1433
1434 @throw type_error.301 if @a type_deduction is `false`, @a manual_type is
1435 `value_t::object`, but @a init contains an element which is not a pair
1436 whose first element is a string. In this case, the constructor could not
1437 create an object. If @a type_deduction would have be `true`, an array
1438 would have been created. See @ref object(initializer_list_t)
1439 for an example.
1440
1441 @complexity Linear in the size of the initializer list @a init.
1442
1443 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
1444 changes to any JSON value.
1445
1446 @liveexample{The example below shows how JSON values are created from
1447 initializer lists.,basic_json__list_init_t}
1448
1449 @sa @ref array(initializer_list_t) -- create a JSON array
1450 value from an initializer list
1451 @sa @ref object(initializer_list_t) -- create a JSON object
1452 value from an initializer list
1453
1454 @since version 1.0.0
1455 */
1456 basic_json(initializer_list_t init,
1457 bool type_deduction = true,
1458 value_t manual_type = value_t::array)
1459 {
1460 // check if each element is an array with two elements whose first
1461 // element is a string
1462 bool is_an_object = std::all_of(init.begin(), init.end(),
1463 [](const detail::json_ref<basic_json>& element_ref)
1464 {
1465 return element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string();
1466 });
1467
1468 // adjust type if type deduction is not wanted
1469 if (not type_deduction)
1470 {
1471 // if array is wanted, do not create an object though possible
1472 if (manual_type == value_t::array)
1473 {
1474 is_an_object = false;
1475 }
1476
1477 // if object is wanted but impossible, throw an exception
1478 if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object and not is_an_object))
1479 {
1480 JSON_THROW(type_error::create(301, "cannot create object from initializer list"));
1481 }
1482 }
1483
1484 if (is_an_object)
1485 {
1486 // the initializer list is a list of pairs -> create object
1487 m_type = value_t::object;
1488 m_value = value_t::object;
1489
1490 std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref)
1491 {
1492 auto element = element_ref.moved_or_copied();
1493 m_value.object->emplace(
1494 std::move(*((*element.m_value.array)[0].m_value.string)),
1495 std::move((*element.m_value.array)[1]));
1496 });
1497 }
1498 else
1499 {
1500 // the initializer list describes an array -> create array
1501 m_type = value_t::array;
1502 m_value.array = create<array_t>(init.begin(), init.end());
1503 }
1504
1505 assert_invariant();
1506 }
1507
1508 /*!
1509 @brief explicitly create an array from an initializer list
1510
1511 Creates a JSON array value from a given initializer list. That is, given a
1512 list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
1513 initializer list is empty, the empty array `[]` is created.
1514
1515 @note This function is only needed to express two edge cases that cannot
1516 be realized with the initializer list constructor (@ref
1517 basic_json(initializer_list_t, bool, value_t)). These cases
1518 are:
1519 1. creating an array whose elements are all pairs whose first element is a
1520 string -- in this case, the initializer list constructor would create an
1521 object, taking the first elements as keys
1522 2. creating an empty array -- passing the empty initializer list to the
1523 initializer list constructor yields an empty object
1524
1525 @param[in] init initializer list with JSON values to create an array from
1526 (optional)
1527
1528 @return JSON array value
1529
1530 @complexity Linear in the size of @a init.
1531
1532 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
1533 changes to any JSON value.
1534
1535 @liveexample{The following code shows an example for the `array`
1536 function.,array}
1537
1538 @sa @ref basic_json(initializer_list_t, bool, value_t) --
1539 create a JSON value from an initializer list
1540 @sa @ref object(initializer_list_t) -- create a JSON object
1541 value from an initializer list
1542
1543 @since version 1.0.0
1544 */
1545 JSON_HEDLEY_WARN_UNUSED_RESULT
1546 static basic_json array(initializer_list_t init = {})
1547 {
1548 return basic_json(init, false, value_t::array);
1549 }
1550
1551 /*!
1552 @brief explicitly create an object from an initializer list
1553
1554 Creates a JSON object value from a given initializer list. The initializer
1555 lists elements must be pairs, and their first elements must be strings. If
1556 the initializer list is empty, the empty object `{}` is created.
1557
1558 @note This function is only added for symmetry reasons. In contrast to the
1559 related function @ref array(initializer_list_t), there are
1560 no cases which can only be expressed by this function. That is, any
1561 initializer list @a init can also be passed to the initializer list
1562 constructor @ref basic_json(initializer_list_t, bool, value_t).
1563
1564 @param[in] init initializer list to create an object from (optional)
1565
1566 @return JSON object value
1567
1568 @throw type_error.301 if @a init is not a list of pairs whose first
1569 elements are strings. In this case, no object can be created. When such a
1570 value is passed to @ref basic_json(initializer_list_t, bool, value_t),
1571 an array would have been created from the passed initializer list @a init.
1572 See example below.
1573
1574 @complexity Linear in the size of @a init.
1575
1576 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
1577 changes to any JSON value.
1578
1579 @liveexample{The following code shows an example for the `object`
1580 function.,object}
1581
1582 @sa @ref basic_json(initializer_list_t, bool, value_t) --
1583 create a JSON value from an initializer list
1584 @sa @ref array(initializer_list_t) -- create a JSON array
1585 value from an initializer list
1586
1587 @since version 1.0.0
1588 */
1589 JSON_HEDLEY_WARN_UNUSED_RESULT
1590 static basic_json object(initializer_list_t init = {})
1591 {
1592 return basic_json(init, false, value_t::object);
1593 }
1594
1595 /*!
1596 @brief construct an array with count copies of given value
1597
1598 Constructs a JSON array value by creating @a cnt copies of a passed value.
1599 In case @a cnt is `0`, an empty array is created.
1600
1601 @param[in] cnt the number of JSON copies of @a val to create
1602 @param[in] val the JSON value to copy
1603
1604 @post `std::distance(begin(),end()) == cnt` holds.
1605
1606 @complexity Linear in @a cnt.
1607
1608 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
1609 changes to any JSON value.
1610
1611 @liveexample{The following code shows examples for the @ref
1612 basic_json(size_type\, const basic_json&)
1613 constructor.,basic_json__size_type_basic_json}
1614
1615 @since version 1.0.0
1616 */
1617 basic_json(size_type cnt, const basic_json& val)
1618 : m_type(value_t::array)
1619 {
1620 m_value.array = create<array_t>(cnt, val);
1621 assert_invariant();
1622 }
1623
1624 /*!
1625 @brief construct a JSON container given an iterator range
1626
1627 Constructs the JSON value with the contents of the range `[first, last)`.
1628 The semantics depends on the different types a JSON value can have:
1629 - In case of a null type, invalid_iterator.206 is thrown.
1630 - In case of other primitive types (number, boolean, or string), @a first
1631 must be `begin()` and @a last must be `end()`. In this case, the value is
1632 copied. Otherwise, invalid_iterator.204 is thrown.
1633 - In case of structured types (array, object), the constructor behaves as
1634 similar versions for `std::vector` or `std::map`; that is, a JSON array
1635 or object is constructed from the values in the range.
1636
1637 @tparam InputIT an input iterator type (@ref iterator or @ref
1638 const_iterator)
1639
1640 @param[in] first begin of the range to copy from (included)
1641 @param[in] last end of the range to copy from (excluded)
1642
1643 @pre Iterators @a first and @a last must be initialized. **This
1644 precondition is enforced with an assertion (see warning).** If
1645 assertions are switched off, a violation of this precondition yields
1646 undefined behavior.
1647
1648 @pre Range `[first, last)` is valid. Usually, this precondition cannot be
1649 checked efficiently. Only certain edge cases are detected; see the
1650 description of the exceptions below. A violation of this precondition
1651 yields undefined behavior.
1652
1653 @warning A precondition is enforced with a runtime assertion that will
1654 result in calling `std::abort` if this precondition is not met.
1655 Assertions can be disabled by defining `NDEBUG` at compile time.
1656 See https://en.cppreference.com/w/cpp/error/assert for more
1657 information.
1658
1659 @throw invalid_iterator.201 if iterators @a first and @a last are not
1660 compatible (i.e., do not belong to the same JSON value). In this case,
1661 the range `[first, last)` is undefined.
1662 @throw invalid_iterator.204 if iterators @a first and @a last belong to a
1663 primitive type (number, boolean, or string), but @a first does not point
1664 to the first element any more. In this case, the range `[first, last)` is
1665 undefined. See example code below.
1666 @throw invalid_iterator.206 if iterators @a first and @a last belong to a
1667 null value. In this case, the range `[first, last)` is undefined.
1668
1669 @complexity Linear in distance between @a first and @a last.
1670
1671 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
1672 changes to any JSON value.
1673
1674 @liveexample{The example below shows several ways to create JSON values by
1675 specifying a subrange with iterators.,basic_json__InputIt_InputIt}
1676
1677 @since version 1.0.0
1678 */
1679 template<class InputIT, typename std::enable_if<
1680 std::is_same<InputIT, typename basic_json_t::iterator>::value or
1681 std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0>
1682 basic_json(InputIT first, InputIT last)
1683 {
1684 assert(first.m_object != nullptr);
1685 assert(last.m_object != nullptr);
1686
1687 // make sure iterator fits the current value
1688 if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
1689 {
1690 JSON_THROW(invalid_iterator::create(201, "iterators are not compatible"));
1691 }
1692
1693 // copy type from first iterator
1694 m_type = first.m_object->m_type;
1695
1696 // check if iterator range is complete for primitive values
1697 switch (m_type)
1698 {
1699 case value_t::boolean:
1700 case value_t::number_float:
1701 case value_t::number_integer:
1702 case value_t::number_unsigned:
1703 case value_t::string:
1704 {
1705 if (JSON_HEDLEY_UNLIKELY(not first.m_it.primitive_iterator.is_begin()
1706 or not last.m_it.primitive_iterator.is_end()))
1707 {
1708 JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
1709 }
1710 break;
1711 }
1712
1713 default:
1714 break;
1715 }
1716
1717 switch (m_type)
1718 {
1719 case value_t::number_integer:
1720 {
1721 m_value.number_integer = first.m_object->m_value.number_integer;
1722 break;
1723 }
1724
1725 case value_t::number_unsigned:
1726 {
1727 m_value.number_unsigned = first.m_object->m_value.number_unsigned;
1728 break;
1729 }
1730
1731 case value_t::number_float:
1732 {
1733 m_value.number_float = first.m_object->m_value.number_float;
1734 break;
1735 }
1736
1737 case value_t::boolean:
1738 {
1739 m_value.boolean = first.m_object->m_value.boolean;
1740 break;
1741 }
1742
1743 case value_t::string:
1744 {
1745 m_value = *first.m_object->m_value.string;
1746 break;
1747 }
1748
1749 case value_t::object:
1750 {
1751 m_value.object = create<object_t>(first.m_it.object_iterator,
1752 last.m_it.object_iterator);
1753 break;
1754 }
1755
1756 case value_t::array:
1757 {
1758 m_value.array = create<array_t>(first.m_it.array_iterator,
1759 last.m_it.array_iterator);
1760 break;
1761 }
1762
1763 default:
1764 JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " +
1765 std::string(first.m_object->type_name())));
1766 }
1767
1768 assert_invariant();
1769 }
1770
1771
1772 ///////////////////////////////////////
1773 // other constructors and destructor //
1774 ///////////////////////////////////////
1775
1776 /// @private
1777 basic_json(const detail::json_ref<basic_json>& ref)
1778 : basic_json(ref.moved_or_copied())
1779 {}
1780
1781 /*!
1782 @brief copy constructor
1783
1784 Creates a copy of a given JSON value.
1785
1786 @param[in] other the JSON value to copy
1787
1788 @post `*this == other`
1789
1790 @complexity Linear in the size of @a other.
1791
1792 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
1793 changes to any JSON value.
1794
1795 @requirement This function helps `basic_json` satisfying the
1796 [Container](https://en.cppreference.com/w/cpp/named_req/Container)
1797 requirements:
1798 - The complexity is linear.
1799 - As postcondition, it holds: `other == basic_json(other)`.
1800
1801 @liveexample{The following code shows an example for the copy
1802 constructor.,basic_json__basic_json}
1803
1804 @since version 1.0.0
1805 */
1806 basic_json(const basic_json& other)
1807 : m_type(other.m_type)
1808 {
1809 // check of passed value is valid
1810 other.assert_invariant();
1811
1812 switch (m_type)
1813 {
1814 case value_t::object:
1815 {
1816 m_value = *other.m_value.object;
1817 break;
1818 }
1819
1820 case value_t::array:
1821 {
1822 m_value = *other.m_value.array;
1823 break;
1824 }
1825
1826 case value_t::string:
1827 {
1828 m_value = *other.m_value.string;
1829 break;
1830 }
1831
1832 case value_t::boolean:
1833 {
1834 m_value = other.m_value.boolean;
1835 break;
1836 }
1837
1838 case value_t::number_integer:
1839 {
1840 m_value = other.m_value.number_integer;
1841 break;
1842 }
1843
1844 case value_t::number_unsigned:
1845 {
1846 m_value = other.m_value.number_unsigned;
1847 break;
1848 }
1849
1850 case value_t::number_float:
1851 {
1852 m_value = other.m_value.number_float;
1853 break;
1854 }
1855
1856 default:
1857 break;
1858 }
1859
1860 assert_invariant();
1861 }
1862
1863 /*!
1864 @brief move constructor
1865
1866 Move constructor. Constructs a JSON value with the contents of the given
1867 value @a other using move semantics. It "steals" the resources from @a
1868 other and leaves it as JSON null value.
1869
1870 @param[in,out] other value to move to this object
1871
1872 @post `*this` has the same value as @a other before the call.
1873 @post @a other is a JSON null value.
1874
1875 @complexity Constant.
1876
1877 @exceptionsafety No-throw guarantee: this constructor never throws
1878 exceptions.
1879
1880 @requirement This function helps `basic_json` satisfying the
1881 [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible)
1882 requirements.
1883
1884 @liveexample{The code below shows the move constructor explicitly called
1885 via std::move.,basic_json__moveconstructor}
1886
1887 @since version 1.0.0
1888 */
1889 basic_json(basic_json&& other) noexcept
1890 : m_type(std::move(other.m_type)),
1891 m_value(std::move(other.m_value))
1892 {
1893 // check that passed value is valid
1894 other.assert_invariant();
1895
1896 // invalidate payload
1897 other.m_type = value_t::null;
1898 other.m_value = {};
1899
1900 assert_invariant();
1901 }
1902
1903 /*!
1904 @brief copy assignment
1905
1906 Copy assignment operator. Copies a JSON value via the "copy and swap"
1907 strategy: It is expressed in terms of the copy constructor, destructor,
1908 and the `swap()` member function.
1909
1910 @param[in] other value to copy from
1911
1912 @complexity Linear.
1913
1914 @requirement This function helps `basic_json` satisfying the
1915 [Container](https://en.cppreference.com/w/cpp/named_req/Container)
1916 requirements:
1917 - The complexity is linear.
1918
1919 @liveexample{The code below shows and example for the copy assignment. It
1920 creates a copy of value `a` which is then swapped with `b`. Finally\, the
1921 copy of `a` (which is the null value after the swap) is
1922 destroyed.,basic_json__copyassignment}
1923
1924 @since version 1.0.0
1925 */
1926 basic_json& operator=(basic_json other) noexcept (
1927 std::is_nothrow_move_constructible<value_t>::value and
1928 std::is_nothrow_move_assignable<value_t>::value and
1929 std::is_nothrow_move_constructible<json_value>::value and
1930 std::is_nothrow_move_assignable<json_value>::value
1931 )
1932 {
1933 // check that passed value is valid
1934 other.assert_invariant();
1935
1936 using std::swap;
1937 swap(m_type, other.m_type);
1938 swap(m_value, other.m_value);
1939
1940 assert_invariant();
1941 return *this;
1942 }
1943
1944 /*!
1945 @brief destructor
1946
1947 Destroys the JSON value and frees all allocated memory.
1948
1949 @complexity Linear.
1950
1951 @requirement This function helps `basic_json` satisfying the
1952 [Container](https://en.cppreference.com/w/cpp/named_req/Container)
1953 requirements:
1954 - The complexity is linear.
1955 - All stored elements are destroyed and all memory is freed.
1956
1957 @since version 1.0.0
1958 */
1959 ~basic_json() noexcept
1960 {
1961 assert_invariant();
1962 m_value.destroy(m_type);
1963 }
1964
1965 /// @}
1966
1967 public:
1968 ///////////////////////
1969 // object inspection //
1970 ///////////////////////
1971
1972 /// @name object inspection
1973 /// Functions to inspect the type of a JSON value.
1974 /// @{
1975
1976 /*!
1977 @brief serialization
1978
1979 Serialization function for JSON values. The function tries to mimic
1980 Python's `json.dumps()` function, and currently supports its @a indent
1981 and @a ensure_ascii parameters.
1982
1983 @param[in] indent If indent is nonnegative, then array elements and object
1984 members will be pretty-printed with that indent level. An indent level of
1985 `0` will only insert newlines. `-1` (the default) selects the most compact
1986 representation.
1987 @param[in] indent_char The character to use for indentation if @a indent is
1988 greater than `0`. The default is ` ` (space).
1989 @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters
1990 in the output are escaped with `\uXXXX` sequences, and the result consists
1991 of ASCII characters only.
1992 @param[in] error_handler how to react on decoding errors; there are three
1993 possible values: `strict` (throws and exception in case a decoding error
1994 occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD),
1995 and `ignore` (ignore invalid UTF-8 sequences during serialization).
1996
1997 @return string containing the serialization of the JSON value
1998
1999 @throw type_error.316 if a string stored inside the JSON value is not
2000 UTF-8 encoded
2001
2002 @complexity Linear.
2003
2004 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
2005 changes in the JSON value.
2006
2007 @liveexample{The following example shows the effect of different @a indent\,
2008 @a indent_char\, and @a ensure_ascii parameters to the result of the
2009 serialization.,dump}
2010
2011 @see https://docs.python.org/2/library/json.html#json.dump
2012
2013 @since version 1.0.0; indentation character @a indent_char, option
2014 @a ensure_ascii and exceptions added in version 3.0.0; error
2015 handlers added in version 3.4.0.
2016 */
2017 string_t dump(const int indent = -1,
2018 const char indent_char = ' ',
2019 const bool ensure_ascii = false,
2020 const error_handler_t error_handler = error_handler_t::strict) const
2021 {
2022 string_t result;
2023 serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler);
2024
2025 if (indent >= 0)
2026 {
2027 s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent));
2028 }
2029 else
2030 {
2031 s.dump(*this, false, ensure_ascii, 0);
2032 }
2033
2034 return result;
2035 }
2036
2037 /*!
2038 @brief return the type of the JSON value (explicit)
2039
2040 Return the type of the JSON value as a value from the @ref value_t
2041 enumeration.
2042
2043 @return the type of the JSON value
2044 Value type | return value
2045 ------------------------- | -------------------------
2046 null | value_t::null
2047 boolean | value_t::boolean
2048 string | value_t::string
2049 number (integer) | value_t::number_integer
2050 number (unsigned integer) | value_t::number_unsigned
2051 number (floating-point) | value_t::number_float
2052 object | value_t::object
2053 array | value_t::array
2054 discarded | value_t::discarded
2055
2056 @complexity Constant.
2057
2058 @exceptionsafety No-throw guarantee: this member function never throws
2059 exceptions.
2060
2061 @liveexample{The following code exemplifies `type()` for all JSON
2062 types.,type}
2063
2064 @sa @ref operator value_t() -- return the type of the JSON value (implicit)
2065 @sa @ref type_name() -- return the type as string
2066
2067 @since version 1.0.0
2068 */
2069 constexpr value_t type() const noexcept
2070 {
2071 return m_type;
2072 }
2073
2074 /*!
2075 @brief return whether type is primitive
2076
2077 This function returns true if and only if the JSON type is primitive
2078 (string, number, boolean, or null).
2079
2080 @return `true` if type is primitive (string, number, boolean, or null),
2081 `false` otherwise.
2082
2083 @complexity Constant.
2084
2085 @exceptionsafety No-throw guarantee: this member function never throws
2086 exceptions.
2087
2088 @liveexample{The following code exemplifies `is_primitive()` for all JSON
2089 types.,is_primitive}
2090
2091 @sa @ref is_structured() -- returns whether JSON value is structured
2092 @sa @ref is_null() -- returns whether JSON value is `null`
2093 @sa @ref is_string() -- returns whether JSON value is a string
2094 @sa @ref is_boolean() -- returns whether JSON value is a boolean
2095 @sa @ref is_number() -- returns whether JSON value is a number
2096
2097 @since version 1.0.0
2098 */
2099 constexpr bool is_primitive() const noexcept
2100 {
2101 return is_null() or is_string() or is_boolean() or is_number();
2102 }
2103
2104 /*!
2105 @brief return whether type is structured
2106
2107 This function returns true if and only if the JSON type is structured
2108 (array or object).
2109
2110 @return `true` if type is structured (array or object), `false` otherwise.
2111
2112 @complexity Constant.
2113
2114 @exceptionsafety No-throw guarantee: this member function never throws
2115 exceptions.
2116
2117 @liveexample{The following code exemplifies `is_structured()` for all JSON
2118 types.,is_structured}
2119
2120 @sa @ref is_primitive() -- returns whether value is primitive
2121 @sa @ref is_array() -- returns whether value is an array
2122 @sa @ref is_object() -- returns whether value is an object
2123
2124 @since version 1.0.0
2125 */
2126 constexpr bool is_structured() const noexcept
2127 {
2128 return is_array() or is_object();
2129 }
2130
2131 /*!
2132 @brief return whether value is null
2133
2134 This function returns true if and only if the JSON value is null.
2135
2136 @return `true` if type is null, `false` otherwise.
2137
2138 @complexity Constant.
2139
2140 @exceptionsafety No-throw guarantee: this member function never throws
2141 exceptions.
2142
2143 @liveexample{The following code exemplifies `is_null()` for all JSON
2144 types.,is_null}
2145
2146 @since version 1.0.0
2147 */
2148 constexpr bool is_null() const noexcept
2149 {
2150 return m_type == value_t::null;
2151 }
2152
2153 /*!
2154 @brief return whether value is a boolean
2155
2156 This function returns true if and only if the JSON value is a boolean.
2157
2158 @return `true` if type is boolean, `false` otherwise.
2159
2160 @complexity Constant.
2161
2162 @exceptionsafety No-throw guarantee: this member function never throws
2163 exceptions.
2164
2165 @liveexample{The following code exemplifies `is_boolean()` for all JSON
2166 types.,is_boolean}
2167
2168 @since version 1.0.0
2169 */
2170 constexpr bool is_boolean() const noexcept
2171 {
2172 return m_type == value_t::boolean;
2173 }
2174
2175 /*!
2176 @brief return whether value is a number
2177
2178 This function returns true if and only if the JSON value is a number. This
2179 includes both integer (signed and unsigned) and floating-point values.
2180
2181 @return `true` if type is number (regardless whether integer, unsigned
2182 integer or floating-type), `false` otherwise.
2183
2184 @complexity Constant.
2185
2186 @exceptionsafety No-throw guarantee: this member function never throws
2187 exceptions.
2188
2189 @liveexample{The following code exemplifies `is_number()` for all JSON
2190 types.,is_number}
2191
2192 @sa @ref is_number_integer() -- check if value is an integer or unsigned
2193 integer number
2194 @sa @ref is_number_unsigned() -- check if value is an unsigned integer
2195 number
2196 @sa @ref is_number_float() -- check if value is a floating-point number
2197
2198 @since version 1.0.0
2199 */
2200 constexpr bool is_number() const noexcept
2201 {
2202 return is_number_integer() or is_number_float();
2203 }
2204
2205 /*!
2206 @brief return whether value is an integer number
2207
2208 This function returns true if and only if the JSON value is a signed or
2209 unsigned integer number. This excludes floating-point values.
2210
2211 @return `true` if type is an integer or unsigned integer number, `false`
2212 otherwise.
2213
2214 @complexity Constant.
2215
2216 @exceptionsafety No-throw guarantee: this member function never throws
2217 exceptions.
2218
2219 @liveexample{The following code exemplifies `is_number_integer()` for all
2220 JSON types.,is_number_integer}
2221
2222 @sa @ref is_number() -- check if value is a number
2223 @sa @ref is_number_unsigned() -- check if value is an unsigned integer
2224 number
2225 @sa @ref is_number_float() -- check if value is a floating-point number
2226
2227 @since version 1.0.0
2228 */
2229 constexpr bool is_number_integer() const noexcept
2230 {
2231 return m_type == value_t::number_integer or m_type == value_t::number_unsigned;
2232 }
2233
2234 /*!
2235 @brief return whether value is an unsigned integer number
2236
2237 This function returns true if and only if the JSON value is an unsigned
2238 integer number. This excludes floating-point and signed integer values.
2239
2240 @return `true` if type is an unsigned integer number, `false` otherwise.
2241
2242 @complexity Constant.
2243
2244 @exceptionsafety No-throw guarantee: this member function never throws
2245 exceptions.
2246
2247 @liveexample{The following code exemplifies `is_number_unsigned()` for all
2248 JSON types.,is_number_unsigned}
2249
2250 @sa @ref is_number() -- check if value is a number
2251 @sa @ref is_number_integer() -- check if value is an integer or unsigned
2252 integer number
2253 @sa @ref is_number_float() -- check if value is a floating-point number
2254
2255 @since version 2.0.0
2256 */
2257 constexpr bool is_number_unsigned() const noexcept
2258 {
2259 return m_type == value_t::number_unsigned;
2260 }
2261
2262 /*!
2263 @brief return whether value is a floating-point number
2264
2265 This function returns true if and only if the JSON value is a
2266 floating-point number. This excludes signed and unsigned integer values.
2267
2268 @return `true` if type is a floating-point number, `false` otherwise.
2269
2270 @complexity Constant.
2271
2272 @exceptionsafety No-throw guarantee: this member function never throws
2273 exceptions.
2274
2275 @liveexample{The following code exemplifies `is_number_float()` for all
2276 JSON types.,is_number_float}
2277
2278 @sa @ref is_number() -- check if value is number
2279 @sa @ref is_number_integer() -- check if value is an integer number
2280 @sa @ref is_number_unsigned() -- check if value is an unsigned integer
2281 number
2282
2283 @since version 1.0.0
2284 */
2285 constexpr bool is_number_float() const noexcept
2286 {
2287 return m_type == value_t::number_float;
2288 }
2289
2290 /*!
2291 @brief return whether value is an object
2292
2293 This function returns true if and only if the JSON value is an object.
2294
2295 @return `true` if type is object, `false` otherwise.
2296
2297 @complexity Constant.
2298
2299 @exceptionsafety No-throw guarantee: this member function never throws
2300 exceptions.
2301
2302 @liveexample{The following code exemplifies `is_object()` for all JSON
2303 types.,is_object}
2304
2305 @since version 1.0.0
2306 */
2307 constexpr bool is_object() const noexcept
2308 {
2309 return m_type == value_t::object;
2310 }
2311
2312 /*!
2313 @brief return whether value is an array
2314
2315 This function returns true if and only if the JSON value is an array.
2316
2317 @return `true` if type is array, `false` otherwise.
2318
2319 @complexity Constant.
2320
2321 @exceptionsafety No-throw guarantee: this member function never throws
2322 exceptions.
2323
2324 @liveexample{The following code exemplifies `is_array()` for all JSON
2325 types.,is_array}
2326
2327 @since version 1.0.0
2328 */
2329 constexpr bool is_array() const noexcept
2330 {
2331 return m_type == value_t::array;
2332 }
2333
2334 /*!
2335 @brief return whether value is a string
2336
2337 This function returns true if and only if the JSON value is a string.
2338
2339 @return `true` if type is string, `false` otherwise.
2340
2341 @complexity Constant.
2342
2343 @exceptionsafety No-throw guarantee: this member function never throws
2344 exceptions.
2345
2346 @liveexample{The following code exemplifies `is_string()` for all JSON
2347 types.,is_string}
2348
2349 @since version 1.0.0
2350 */
2351 constexpr bool is_string() const noexcept
2352 {
2353 return m_type == value_t::string;
2354 }
2355
2356 /*!
2357 @brief return whether value is discarded
2358
2359 This function returns true if and only if the JSON value was discarded
2360 during parsing with a callback function (see @ref parser_callback_t).
2361
2362 @note This function will always be `false` for JSON values after parsing.
2363 That is, discarded values can only occur during parsing, but will be
2364 removed when inside a structured value or replaced by null in other cases.
2365
2366 @return `true` if type is discarded, `false` otherwise.
2367
2368 @complexity Constant.
2369
2370 @exceptionsafety No-throw guarantee: this member function never throws
2371 exceptions.
2372
2373 @liveexample{The following code exemplifies `is_discarded()` for all JSON
2374 types.,is_discarded}
2375
2376 @since version 1.0.0
2377 */
2378 constexpr bool is_discarded() const noexcept
2379 {
2380 return m_type == value_t::discarded;
2381 }
2382
2383 /*!
2384 @brief return the type of the JSON value (implicit)
2385
2386 Implicitly return the type of the JSON value as a value from the @ref
2387 value_t enumeration.
2388
2389 @return the type of the JSON value
2390
2391 @complexity Constant.
2392
2393 @exceptionsafety No-throw guarantee: this member function never throws
2394 exceptions.
2395
2396 @liveexample{The following code exemplifies the @ref value_t operator for
2397 all JSON types.,operator__value_t}
2398
2399 @sa @ref type() -- return the type of the JSON value (explicit)
2400 @sa @ref type_name() -- return the type as string
2401
2402 @since version 1.0.0
2403 */
2404 constexpr operator value_t() const noexcept
2405 {
2406 return m_type;
2407 }
2408
2409 /// @}
2410
2411 private:
2412 //////////////////
2413 // value access //
2414 //////////////////
2415
2416 /// get a boolean (explicit)
2417 boolean_t get_impl(boolean_t* /*unused*/) const
2418 {
2419 if (JSON_HEDLEY_LIKELY(is_boolean()))
2420 {
2421 return m_value.boolean;
2422 }
2423
2424 JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name())));
2425 }
2426
2427 /// get a pointer to the value (object)
2428 object_t* get_impl_ptr(object_t* /*unused*/) noexcept
2429 {
2430 return is_object() ? m_value.object : nullptr;
2431 }
2432
2433 /// get a pointer to the value (object)
2434 constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept
2435 {
2436 return is_object() ? m_value.object : nullptr;
2437 }
2438
2439 /// get a pointer to the value (array)
2440 array_t* get_impl_ptr(array_t* /*unused*/) noexcept
2441 {
2442 return is_array() ? m_value.array : nullptr;
2443 }
2444
2445 /// get a pointer to the value (array)
2446 constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept
2447 {
2448 return is_array() ? m_value.array : nullptr;
2449 }
2450
2451 /// get a pointer to the value (string)
2452 string_t* get_impl_ptr(string_t* /*unused*/) noexcept
2453 {
2454 return is_string() ? m_value.string : nullptr;
2455 }
2456
2457 /// get a pointer to the value (string)
2458 constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept
2459 {
2460 return is_string() ? m_value.string : nullptr;
2461 }
2462
2463 /// get a pointer to the value (boolean)
2464 boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept
2465 {
2466 return is_boolean() ? &m_value.boolean : nullptr;
2467 }
2468
2469 /// get a pointer to the value (boolean)
2470 constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept
2471 {
2472 return is_boolean() ? &m_value.boolean : nullptr;
2473 }
2474
2475 /// get a pointer to the value (integer number)
2476 number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept
2477 {
2478 return is_number_integer() ? &m_value.number_integer : nullptr;
2479 }
2480
2481 /// get a pointer to the value (integer number)
2482 constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept
2483 {
2484 return is_number_integer() ? &m_value.number_integer : nullptr;
2485 }
2486
2487 /// get a pointer to the value (unsigned number)
2488 number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept
2489 {
2490 return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
2491 }
2492
2493 /// get a pointer to the value (unsigned number)
2494 constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept
2495 {
2496 return is_number_unsigned() ? &m_value.number_unsigned : nullptr;
2497 }
2498
2499 /// get a pointer to the value (floating-point number)
2500 number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept
2501 {
2502 return is_number_float() ? &m_value.number_float : nullptr;
2503 }
2504
2505 /// get a pointer to the value (floating-point number)
2506 constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept
2507 {
2508 return is_number_float() ? &m_value.number_float : nullptr;
2509 }
2510
2511 /*!
2512 @brief helper function to implement get_ref()
2513
2514 This function helps to implement get_ref() without code duplication for
2515 const and non-const overloads
2516
2517 @tparam ThisType will be deduced as `basic_json` or `const basic_json`
2518
2519 @throw type_error.303 if ReferenceType does not match underlying value
2520 type of the current JSON
2521 */
2522 template<typename ReferenceType, typename ThisType>
2523 static ReferenceType get_ref_impl(ThisType& obj)
2524 {
2525 // delegate the call to get_ptr<>()
2526 auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>();
2527
2528 if (JSON_HEDLEY_LIKELY(ptr != nullptr))
2529 {
2530 return *ptr;
2531 }
2532
2533 JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name())));
2534 }
2535
2536 public:
2537 /// @name value access
2538 /// Direct access to the stored value of a JSON value.
2539 /// @{
2540
2541 /*!
2542 @brief get special-case overload
2543
2544 This overloads avoids a lot of template boilerplate, it can be seen as the
2545 identity method
2546
2547 @tparam BasicJsonType == @ref basic_json
2548
2549 @return a copy of *this
2550
2551 @complexity Constant.
2552
2553 @since version 2.1.0
2554 */
2555 template<typename BasicJsonType, detail::enable_if_t<
2556 std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value,
2557 int> = 0>
2558 basic_json get() const
2559 {
2560 return *this;
2561 }
2562
2563 /*!
2564 @brief get special-case overload
2565
2566 This overloads converts the current @ref basic_json in a different
2567 @ref basic_json type
2568
2569 @tparam BasicJsonType == @ref basic_json
2570
2571 @return a copy of *this, converted into @tparam BasicJsonType
2572
2573 @complexity Depending on the implementation of the called `from_json()`
2574 method.
2575
2576 @since version 3.2.0
2577 */
2578 template<typename BasicJsonType, detail::enable_if_t<
2579 not std::is_same<BasicJsonType, basic_json>::value and
2580 detail::is_basic_json<BasicJsonType>::value, int> = 0>
2581 BasicJsonType get() const
2582 {
2583 return *this;
2584 }
2585
2586 /*!
2587 @brief get a value (explicit)
2588
2589 Explicit type conversion between the JSON value and a compatible value
2590 which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
2591 and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
2592 The value is converted by calling the @ref json_serializer<ValueType>
2593 `from_json()` method.
2594
2595 The function is equivalent to executing
2596 @code {.cpp}
2597 ValueType ret;
2598 JSONSerializer<ValueType>::from_json(*this, ret);
2599 return ret;
2600 @endcode
2601
2602 This overloads is chosen if:
2603 - @a ValueType is not @ref basic_json,
2604 - @ref json_serializer<ValueType> has a `from_json()` method of the form
2605 `void from_json(const basic_json&, ValueType&)`, and
2606 - @ref json_serializer<ValueType> does not have a `from_json()` method of
2607 the form `ValueType from_json(const basic_json&)`
2608
2609 @tparam ValueTypeCV the provided value type
2610 @tparam ValueType the returned value type
2611
2612 @return copy of the JSON value, converted to @a ValueType
2613
2614 @throw what @ref json_serializer<ValueType> `from_json()` method throws
2615
2616 @liveexample{The example below shows several conversions from JSON values
2617 to other types. There a few things to note: (1) Floating-point numbers can
2618 be converted to integers\, (2) A JSON array can be converted to a standard
2619 `std::vector<short>`\, (3) A JSON object can be converted to C++
2620 associative containers such as `std::unordered_map<std::string\,
2621 json>`.,get__ValueType_const}
2622
2623 @since version 2.1.0
2624 */
2625 template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
2626 detail::enable_if_t <
2627 not detail::is_basic_json<ValueType>::value and
2628 detail::has_from_json<basic_json_t, ValueType>::value and
2629 not detail::has_non_default_from_json<basic_json_t, ValueType>::value,
2630 int> = 0>
2631 ValueType get() const noexcept(noexcept(
2632 JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>())))
2633 {
2634 // we cannot static_assert on ValueTypeCV being non-const, because
2635 // there is support for get<const basic_json_t>(), which is why we
2636 // still need the uncvref
2637 static_assert(not std::is_reference<ValueTypeCV>::value,
2638 "get() cannot be used with reference types, you might want to use get_ref()");
2639 static_assert(std::is_default_constructible<ValueType>::value,
2640 "types must be DefaultConstructible when used with get()");
2641
2642 ValueType ret;
2643 JSONSerializer<ValueType>::from_json(*this, ret);
2644 return ret;
2645 }
2646
2647 /*!
2648 @brief get a value (explicit); special case
2649
2650 Explicit type conversion between the JSON value and a compatible value
2651 which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible)
2652 and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible).
2653 The value is converted by calling the @ref json_serializer<ValueType>
2654 `from_json()` method.
2655
2656 The function is equivalent to executing
2657 @code {.cpp}
2658 return JSONSerializer<ValueTypeCV>::from_json(*this);
2659 @endcode
2660
2661 This overloads is chosen if:
2662 - @a ValueType is not @ref basic_json and
2663 - @ref json_serializer<ValueType> has a `from_json()` method of the form
2664 `ValueType from_json(const basic_json&)`
2665
2666 @note If @ref json_serializer<ValueType> has both overloads of
2667 `from_json()`, this one is chosen.
2668
2669 @tparam ValueTypeCV the provided value type
2670 @tparam ValueType the returned value type
2671
2672 @return copy of the JSON value, converted to @a ValueType
2673
2674 @throw what @ref json_serializer<ValueType> `from_json()` method throws
2675
2676 @since version 2.1.0
2677 */
2678 template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>,
2679 detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and
2680 detail::has_non_default_from_json<basic_json_t, ValueType>::value,
2681 int> = 0>
2682 ValueType get() const noexcept(noexcept(
2683 JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>())))
2684 {
2685 static_assert(not std::is_reference<ValueTypeCV>::value,
2686 "get() cannot be used with reference types, you might want to use get_ref()");
2687 return JSONSerializer<ValueType>::from_json(*this);
2688 }
2689
2690 /*!
2691 @brief get a value (explicit)
2692
2693 Explicit type conversion between the JSON value and a compatible value.
2694 The value is filled into the input parameter by calling the @ref json_serializer<ValueType>
2695 `from_json()` method.
2696
2697 The function is equivalent to executing
2698 @code {.cpp}
2699 ValueType v;
2700 JSONSerializer<ValueType>::from_json(*this, v);
2701 @endcode
2702
2703 This overloads is chosen if:
2704 - @a ValueType is not @ref basic_json,
2705 - @ref json_serializer<ValueType> has a `from_json()` method of the form
2706 `void from_json(const basic_json&, ValueType&)`, and
2707
2708 @tparam ValueType the input parameter type.
2709
2710 @return the input parameter, allowing chaining calls.
2711
2712 @throw what @ref json_serializer<ValueType> `from_json()` method throws
2713
2714 @liveexample{The example below shows several conversions from JSON values
2715 to other types. There a few things to note: (1) Floating-point numbers can
2716 be converted to integers\, (2) A JSON array can be converted to a standard
2717 `std::vector<short>`\, (3) A JSON object can be converted to C++
2718 associative containers such as `std::unordered_map<std::string\,
2719 json>`.,get_to}
2720
2721 @since version 3.3.0
2722 */
2723 template<typename ValueType,
2724 detail::enable_if_t <
2725 not detail::is_basic_json<ValueType>::value and
2726 detail::has_from_json<basic_json_t, ValueType>::value,
2727 int> = 0>
2728 ValueType & get_to(ValueType& v) const noexcept(noexcept(
2729 JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v)))
2730 {
2731 JSONSerializer<ValueType>::from_json(*this, v);
2732 return v;
2733 }
2734
2735 template <
2736 typename T, std::size_t N,
2737 typename Array = T (&)[N],
2738 detail::enable_if_t <
2739 detail::has_from_json<basic_json_t, Array>::value, int > = 0 >
2740 Array get_to(T (&v)[N]) const
2741 noexcept(noexcept(JSONSerializer<Array>::from_json(
2742 std::declval<const basic_json_t&>(), v)))
2743 {
2744 JSONSerializer<Array>::from_json(*this, v);
2745 return v;
2746 }
2747
2748
2749 /*!
2750 @brief get a pointer value (implicit)
2751
2752 Implicit pointer access to the internally stored JSON value. No copies are
2753 made.
2754
2755 @warning Writing data to the pointee of the result yields an undefined
2756 state.
2757
2758 @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
2759 object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
2760 @ref number_unsigned_t, or @ref number_float_t. Enforced by a static
2761 assertion.
2762
2763 @return pointer to the internally stored JSON value if the requested
2764 pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
2765
2766 @complexity Constant.
2767
2768 @liveexample{The example below shows how pointers to internal values of a
2769 JSON value can be requested. Note that no type conversions are made and a
2770 `nullptr` is returned if the value and the requested pointer type does not
2771 match.,get_ptr}
2772
2773 @since version 1.0.0
2774 */
2775 template<typename PointerType, typename std::enable_if<
2776 std::is_pointer<PointerType>::value, int>::type = 0>
2777 auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
2778 {
2779 // delegate the call to get_impl_ptr<>()
2780 return get_impl_ptr(static_cast<PointerType>(nullptr));
2781 }
2782
2783 /*!
2784 @brief get a pointer value (implicit)
2785 @copydoc get_ptr()
2786 */
2787 template<typename PointerType, typename std::enable_if<
2788 std::is_pointer<PointerType>::value and
2789 std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0>
2790 constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>()))
2791 {
2792 // delegate the call to get_impl_ptr<>() const
2793 return get_impl_ptr(static_cast<PointerType>(nullptr));
2794 }
2795
2796 /*!
2797 @brief get a pointer value (explicit)
2798
2799 Explicit pointer access to the internally stored JSON value. No copies are
2800 made.
2801
2802 @warning The pointer becomes invalid if the underlying JSON object
2803 changes.
2804
2805 @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
2806 object_t, @ref string_t, @ref boolean_t, @ref number_integer_t,
2807 @ref number_unsigned_t, or @ref number_float_t.
2808
2809 @return pointer to the internally stored JSON value if the requested
2810 pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
2811
2812 @complexity Constant.
2813
2814 @liveexample{The example below shows how pointers to internal values of a
2815 JSON value can be requested. Note that no type conversions are made and a
2816 `nullptr` is returned if the value and the requested pointer type does not
2817 match.,get__PointerType}
2818
2819 @sa @ref get_ptr() for explicit pointer-member access
2820
2821 @since version 1.0.0
2822 */
2823 template<typename PointerType, typename std::enable_if<
2824 std::is_pointer<PointerType>::value, int>::type = 0>
2825 auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>())
2826 {
2827 // delegate the call to get_ptr
2828 return get_ptr<PointerType>();
2829 }
2830
2831 /*!
2832 @brief get a pointer value (explicit)
2833 @copydoc get()
2834 */
2835 template<typename PointerType, typename std::enable_if<
2836 std::is_pointer<PointerType>::value, int>::type = 0>
2837 constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>())
2838 {
2839 // delegate the call to get_ptr
2840 return get_ptr<PointerType>();
2841 }
2842
2843 /*!
2844 @brief get a reference value (implicit)
2845
2846 Implicit reference access to the internally stored JSON value. No copies
2847 are made.
2848
2849 @warning Writing data to the referee of the result yields an undefined
2850 state.
2851
2852 @tparam ReferenceType reference type; must be a reference to @ref array_t,
2853 @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or
2854 @ref number_float_t. Enforced by static assertion.
2855
2856 @return reference to the internally stored JSON value if the requested
2857 reference type @a ReferenceType fits to the JSON value; throws
2858 type_error.303 otherwise
2859
2860 @throw type_error.303 in case passed type @a ReferenceType is incompatible
2861 with the stored JSON value; see example below
2862
2863 @complexity Constant.
2864
2865 @liveexample{The example shows several calls to `get_ref()`.,get_ref}
2866
2867 @since version 1.1.0
2868 */
2869 template<typename ReferenceType, typename std::enable_if<
2870 std::is_reference<ReferenceType>::value, int>::type = 0>
2871 ReferenceType get_ref()
2872 {
2873 // delegate call to get_ref_impl
2874 return get_ref_impl<ReferenceType>(*this);
2875 }
2876
2877 /*!
2878 @brief get a reference value (implicit)
2879 @copydoc get_ref()
2880 */
2881 template<typename ReferenceType, typename std::enable_if<
2882 std::is_reference<ReferenceType>::value and
2883 std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0>
2884 ReferenceType get_ref() const
2885 {
2886 // delegate call to get_ref_impl
2887 return get_ref_impl<ReferenceType>(*this);
2888 }
2889
2890 /*!
2891 @brief get a value (implicit)
2892
2893 Implicit type conversion between the JSON value and a compatible value.
2894 The call is realized by calling @ref get() const.
2895
2896 @tparam ValueType non-pointer type compatible to the JSON value, for
2897 instance `int` for JSON integer numbers, `bool` for JSON booleans, or
2898 `std::vector` types for JSON arrays. The character type of @ref string_t
2899 as well as an initializer list of this type is excluded to avoid
2900 ambiguities as these types implicitly convert to `std::string`.
2901
2902 @return copy of the JSON value, converted to type @a ValueType
2903
2904 @throw type_error.302 in case passed type @a ValueType is incompatible
2905 to the JSON value type (e.g., the JSON value is of type boolean, but a
2906 string is requested); see example below
2907
2908 @complexity Linear in the size of the JSON value.
2909
2910 @liveexample{The example below shows several conversions from JSON values
2911 to other types. There a few things to note: (1) Floating-point numbers can
2912 be converted to integers\, (2) A JSON array can be converted to a standard
2913 `std::vector<short>`\, (3) A JSON object can be converted to C++
2914 associative containers such as `std::unordered_map<std::string\,
2915 json>`.,operator__ValueType}
2916
2917 @since version 1.0.0
2918 */
2919 template < typename ValueType, typename std::enable_if <
2920 not std::is_pointer<ValueType>::value and
2921 not std::is_same<ValueType, detail::json_ref<basic_json>>::value and
2922 not std::is_same<ValueType, typename string_t::value_type>::value and
2923 not detail::is_basic_json<ValueType>::value
2924
2925 #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015
2926 and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
2927 #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) and _MSC_VER <= 1914))
2928 and not std::is_same<ValueType, typename std::string_view>::value
2929 #endif
2930 #endif
2931 and detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value
2932 , int >::type = 0 >
2933 operator ValueType() const
2934 {
2935 // delegate the call to get<>() const
2936 return get<ValueType>();
2937 }
2938
2939 /// @}
2940
2941
2942 ////////////////////
2943 // element access //
2944 ////////////////////
2945
2946 /// @name element access
2947 /// Access to the JSON value.
2948 /// @{
2949
2950 /*!
2951 @brief access specified array element with bounds checking
2952
2953 Returns a reference to the element at specified location @a idx, with
2954 bounds checking.
2955
2956 @param[in] idx index of the element to access
2957
2958 @return reference to the element at index @a idx
2959
2960 @throw type_error.304 if the JSON value is not an array; in this case,
2961 calling `at` with an index makes no sense. See example below.
2962 @throw out_of_range.401 if the index @a idx is out of range of the array;
2963 that is, `idx >= size()`. See example below.
2964
2965 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
2966 changes in the JSON value.
2967
2968 @complexity Constant.
2969
2970 @since version 1.0.0
2971
2972 @liveexample{The example below shows how array elements can be read and
2973 written using `at()`. It also demonstrates the different exceptions that
2974 can be thrown.,at__size_type}
2975 */
2976 reference at(size_type idx)
2977 {
2978 // at only works for arrays
2979 if (JSON_HEDLEY_LIKELY(is_array()))
2980 {
2981 JSON_TRY
2982 {
2983 return m_value.array->at(idx);
2984 }
2985 JSON_CATCH (std::out_of_range&)
2986 {
2987 // create better exception explanation
2988 JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
2989 }
2990 }
2991 else
2992 {
2993 JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
2994 }
2995 }
2996
2997 /*!
2998 @brief access specified array element with bounds checking
2999
3000 Returns a const reference to the element at specified location @a idx,
3001 with bounds checking.
3002
3003 @param[in] idx index of the element to access
3004
3005 @return const reference to the element at index @a idx
3006
3007 @throw type_error.304 if the JSON value is not an array; in this case,
3008 calling `at` with an index makes no sense. See example below.
3009 @throw out_of_range.401 if the index @a idx is out of range of the array;
3010 that is, `idx >= size()`. See example below.
3011
3012 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
3013 changes in the JSON value.
3014
3015 @complexity Constant.
3016
3017 @since version 1.0.0
3018
3019 @liveexample{The example below shows how array elements can be read using
3020 `at()`. It also demonstrates the different exceptions that can be thrown.,
3021 at__size_type_const}
3022 */
3023 const_reference at(size_type idx) const
3024 {
3025 // at only works for arrays
3026 if (JSON_HEDLEY_LIKELY(is_array()))
3027 {
3028 JSON_TRY
3029 {
3030 return m_value.array->at(idx);
3031 }
3032 JSON_CATCH (std::out_of_range&)
3033 {
3034 // create better exception explanation
3035 JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
3036 }
3037 }
3038 else
3039 {
3040 JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
3041 }
3042 }
3043
3044 /*!
3045 @brief access specified object element with bounds checking
3046
3047 Returns a reference to the element at with specified key @a key, with
3048 bounds checking.
3049
3050 @param[in] key key of the element to access
3051
3052 @return reference to the element at key @a key
3053
3054 @throw type_error.304 if the JSON value is not an object; in this case,
3055 calling `at` with a key makes no sense. See example below.
3056 @throw out_of_range.403 if the key @a key is is not stored in the object;
3057 that is, `find(key) == end()`. See example below.
3058
3059 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
3060 changes in the JSON value.
3061
3062 @complexity Logarithmic in the size of the container.
3063
3064 @sa @ref operator[](const typename object_t::key_type&) for unchecked
3065 access by reference
3066 @sa @ref value() for access by value with a default value
3067
3068 @since version 1.0.0
3069
3070 @liveexample{The example below shows how object elements can be read and
3071 written using `at()`. It also demonstrates the different exceptions that
3072 can be thrown.,at__object_t_key_type}
3073 */
3074 reference at(const typename object_t::key_type& key)
3075 {
3076 // at only works for objects
3077 if (JSON_HEDLEY_LIKELY(is_object()))
3078 {
3079 JSON_TRY
3080 {
3081 return m_value.object->at(key);
3082 }
3083 JSON_CATCH (std::out_of_range&)
3084 {
3085 // create better exception explanation
3086 JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
3087 }
3088 }
3089 else
3090 {
3091 JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
3092 }
3093 }
3094
3095 /*!
3096 @brief access specified object element with bounds checking
3097
3098 Returns a const reference to the element at with specified key @a key,
3099 with bounds checking.
3100
3101 @param[in] key key of the element to access
3102
3103 @return const reference to the element at key @a key
3104
3105 @throw type_error.304 if the JSON value is not an object; in this case,
3106 calling `at` with a key makes no sense. See example below.
3107 @throw out_of_range.403 if the key @a key is is not stored in the object;
3108 that is, `find(key) == end()`. See example below.
3109
3110 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
3111 changes in the JSON value.
3112
3113 @complexity Logarithmic in the size of the container.
3114
3115 @sa @ref operator[](const typename object_t::key_type&) for unchecked
3116 access by reference
3117 @sa @ref value() for access by value with a default value
3118
3119 @since version 1.0.0
3120
3121 @liveexample{The example below shows how object elements can be read using
3122 `at()`. It also demonstrates the different exceptions that can be thrown.,
3123 at__object_t_key_type_const}
3124 */
3125 const_reference at(const typename object_t::key_type& key) const
3126 {
3127 // at only works for objects
3128 if (JSON_HEDLEY_LIKELY(is_object()))
3129 {
3130 JSON_TRY
3131 {
3132 return m_value.object->at(key);
3133 }
3134 JSON_CATCH (std::out_of_range&)
3135 {
3136 // create better exception explanation
3137 JSON_THROW(out_of_range::create(403, "key '" + key + "' not found"));
3138 }
3139 }
3140 else
3141 {
3142 JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name())));
3143 }
3144 }
3145
3146 /*!
3147 @brief access specified array element
3148
3149 Returns a reference to the element at specified location @a idx.
3150
3151 @note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
3152 then the array is silently filled up with `null` values to make `idx` a
3153 valid reference to the last stored element.
3154
3155 @param[in] idx index of the element to access
3156
3157 @return reference to the element at index @a idx
3158
3159 @throw type_error.305 if the JSON value is not an array or null; in that
3160 cases, using the [] operator with an index makes no sense.
3161
3162 @complexity Constant if @a idx is in the range of the array. Otherwise
3163 linear in `idx - size()`.
3164
3165 @liveexample{The example below shows how array elements can be read and
3166 written using `[]` operator. Note the addition of `null`
3167 values.,operatorarray__size_type}
3168
3169 @since version 1.0.0
3170 */
3171 reference operator[](size_type idx)
3172 {
3173 // implicitly convert null value to an empty array
3174 if (is_null())
3175 {
3176 m_type = value_t::array;
3177 m_value.array = create<array_t>();
3178 assert_invariant();
3179 }
3180
3181 // operator[] only works for arrays
3182 if (JSON_HEDLEY_LIKELY(is_array()))
3183 {
3184 // fill up array with null values if given idx is outside range
3185 if (idx >= m_value.array->size())
3186 {
3187 m_value.array->insert(m_value.array->end(),
3188 idx - m_value.array->size() + 1,
3189 basic_json());
3190 }
3191
3192 return m_value.array->operator[](idx);
3193 }
3194
3195 JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
3196 }
3197
3198 /*!
3199 @brief access specified array element
3200
3201 Returns a const reference to the element at specified location @a idx.
3202
3203 @param[in] idx index of the element to access
3204
3205 @return const reference to the element at index @a idx
3206
3207 @throw type_error.305 if the JSON value is not an array; in that case,
3208 using the [] operator with an index makes no sense.
3209
3210 @complexity Constant.
3211
3212 @liveexample{The example below shows how array elements can be read using
3213 the `[]` operator.,operatorarray__size_type_const}
3214
3215 @since version 1.0.0
3216 */
3217 const_reference operator[](size_type idx) const
3218 {
3219 // const operator[] only works for arrays
3220 if (JSON_HEDLEY_LIKELY(is_array()))
3221 {
3222 return m_value.array->operator[](idx);
3223 }
3224
3225 JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name())));
3226 }
3227
3228 /*!
3229 @brief access specified object element
3230
3231 Returns a reference to the element at with specified key @a key.
3232
3233 @note If @a key is not found in the object, then it is silently added to
3234 the object and filled with a `null` value to make `key` a valid reference.
3235 In case the value was `null` before, it is converted to an object.
3236
3237 @param[in] key key of the element to access
3238
3239 @return reference to the element at key @a key
3240
3241 @throw type_error.305 if the JSON value is not an object or null; in that
3242 cases, using the [] operator with a key makes no sense.
3243
3244 @complexity Logarithmic in the size of the container.
3245
3246 @liveexample{The example below shows how object elements can be read and
3247 written using the `[]` operator.,operatorarray__key_type}
3248
3249 @sa @ref at(const typename object_t::key_type&) for access by reference
3250 with range checking
3251 @sa @ref value() for access by value with a default value
3252
3253 @since version 1.0.0
3254 */
3255 reference operator[](const typename object_t::key_type& key)
3256 {
3257 // implicitly convert null value to an empty object
3258 if (is_null())
3259 {
3260 m_type = value_t::object;
3261 m_value.object = create<object_t>();
3262 assert_invariant();
3263 }
3264
3265 // operator[] only works for objects
3266 if (JSON_HEDLEY_LIKELY(is_object()))
3267 {
3268 return m_value.object->operator[](key);
3269 }
3270
3271 JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
3272 }
3273
3274 /*!
3275 @brief read-only access specified object element
3276
3277 Returns a const reference to the element at with specified key @a key. No
3278 bounds checking is performed.
3279
3280 @warning If the element with key @a key does not exist, the behavior is
3281 undefined.
3282
3283 @param[in] key key of the element to access
3284
3285 @return const reference to the element at key @a key
3286
3287 @pre The element with key @a key must exist. **This precondition is
3288 enforced with an assertion.**
3289
3290 @throw type_error.305 if the JSON value is not an object; in that case,
3291 using the [] operator with a key makes no sense.
3292
3293 @complexity Logarithmic in the size of the container.
3294
3295 @liveexample{The example below shows how object elements can be read using
3296 the `[]` operator.,operatorarray__key_type_const}
3297
3298 @sa @ref at(const typename object_t::key_type&) for access by reference
3299 with range checking
3300 @sa @ref value() for access by value with a default value
3301
3302 @since version 1.0.0
3303 */
3304 const_reference operator[](const typename object_t::key_type& key) const
3305 {
3306 // const operator[] only works for objects
3307 if (JSON_HEDLEY_LIKELY(is_object()))
3308 {
3309 assert(m_value.object->find(key) != m_value.object->end());
3310 return m_value.object->find(key)->second;
3311 }
3312
3313 JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
3314 }
3315
3316 /*!
3317 @brief access specified object element
3318
3319 Returns a reference to the element at with specified key @a key.
3320
3321 @note If @a key is not found in the object, then it is silently added to
3322 the object and filled with a `null` value to make `key` a valid reference.
3323 In case the value was `null` before, it is converted to an object.
3324
3325 @param[in] key key of the element to access
3326
3327 @return reference to the element at key @a key
3328
3329 @throw type_error.305 if the JSON value is not an object or null; in that
3330 cases, using the [] operator with a key makes no sense.
3331
3332 @complexity Logarithmic in the size of the container.
3333
3334 @liveexample{The example below shows how object elements can be read and
3335 written using the `[]` operator.,operatorarray__key_type}
3336
3337 @sa @ref at(const typename object_t::key_type&) for access by reference
3338 with range checking
3339 @sa @ref value() for access by value with a default value
3340
3341 @since version 1.1.0
3342 */
3343 template<typename T>
3344 JSON_HEDLEY_NON_NULL(2)
3345 reference operator[](T* key)
3346 {
3347 // implicitly convert null to object
3348 if (is_null())
3349 {
3350 m_type = value_t::object;
3351 m_value = value_t::object;
3352 assert_invariant();
3353 }
3354
3355 // at only works for objects
3356 if (JSON_HEDLEY_LIKELY(is_object()))
3357 {
3358 return m_value.object->operator[](key);
3359 }
3360
3361 JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
3362 }
3363
3364 /*!
3365 @brief read-only access specified object element
3366
3367 Returns a const reference to the element at with specified key @a key. No
3368 bounds checking is performed.
3369
3370 @warning If the element with key @a key does not exist, the behavior is
3371 undefined.
3372
3373 @param[in] key key of the element to access
3374
3375 @return const reference to the element at key @a key
3376
3377 @pre The element with key @a key must exist. **This precondition is
3378 enforced with an assertion.**
3379
3380 @throw type_error.305 if the JSON value is not an object; in that case,
3381 using the [] operator with a key makes no sense.
3382
3383 @complexity Logarithmic in the size of the container.
3384
3385 @liveexample{The example below shows how object elements can be read using
3386 the `[]` operator.,operatorarray__key_type_const}
3387
3388 @sa @ref at(const typename object_t::key_type&) for access by reference
3389 with range checking
3390 @sa @ref value() for access by value with a default value
3391
3392 @since version 1.1.0
3393 */
3394 template<typename T>
3395 JSON_HEDLEY_NON_NULL(2)
3396 const_reference operator[](T* key) const
3397 {
3398 // at only works for objects
3399 if (JSON_HEDLEY_LIKELY(is_object()))
3400 {
3401 assert(m_value.object->find(key) != m_value.object->end());
3402 return m_value.object->find(key)->second;
3403 }
3404
3405 JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name())));
3406 }
3407
3408 /*!
3409 @brief access specified object element with default value
3410
3411 Returns either a copy of an object's element at the specified key @a key
3412 or a given default value if no element with key @a key exists.
3413
3414 The function is basically equivalent to executing
3415 @code {.cpp}
3416 try {
3417 return at(key);
3418 } catch(out_of_range) {
3419 return default_value;
3420 }
3421 @endcode
3422
3423 @note Unlike @ref at(const typename object_t::key_type&), this function
3424 does not throw if the given key @a key was not found.
3425
3426 @note Unlike @ref operator[](const typename object_t::key_type& key), this
3427 function does not implicitly add an element to the position defined by @a
3428 key. This function is furthermore also applicable to const objects.
3429
3430 @param[in] key key of the element to access
3431 @param[in] default_value the value to return if @a key is not found
3432
3433 @tparam ValueType type compatible to JSON values, for instance `int` for
3434 JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
3435 JSON arrays. Note the type of the expected value at @a key and the default
3436 value @a default_value must be compatible.
3437
3438 @return copy of the element at key @a key or @a default_value if @a key
3439 is not found
3440
3441 @throw type_error.302 if @a default_value does not match the type of the
3442 value at @a key
3443 @throw type_error.306 if the JSON value is not an object; in that case,
3444 using `value()` with a key makes no sense.
3445
3446 @complexity Logarithmic in the size of the container.
3447
3448 @liveexample{The example below shows how object elements can be queried
3449 with a default value.,basic_json__value}
3450
3451 @sa @ref at(const typename object_t::key_type&) for access by reference
3452 with range checking
3453 @sa @ref operator[](const typename object_t::key_type&) for unchecked
3454 access by reference
3455
3456 @since version 1.0.0
3457 */
3458 template<class ValueType, typename std::enable_if<
3459 std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
3460 ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const
3461 {
3462 // at only works for objects
3463 if (JSON_HEDLEY_LIKELY(is_object()))
3464 {
3465 // if key is found, return value and given default value otherwise
3466 const auto it = find(key);
3467 if (it != end())
3468 {
3469 return *it;
3470 }
3471
3472 return default_value;
3473 }
3474
3475 JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
3476 }
3477
3478 /*!
3479 @brief overload for a default value of type const char*
3480 @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const
3481 */
3482 string_t value(const typename object_t::key_type& key, const char* default_value) const
3483 {
3484 return value(key, string_t(default_value));
3485 }
3486
3487 /*!
3488 @brief access specified object element via JSON Pointer with default value
3489
3490 Returns either a copy of an object's element at the specified key @a key
3491 or a given default value if no element with key @a key exists.
3492
3493 The function is basically equivalent to executing
3494 @code {.cpp}
3495 try {
3496 return at(ptr);
3497 } catch(out_of_range) {
3498 return default_value;
3499 }
3500 @endcode
3501
3502 @note Unlike @ref at(const json_pointer&), this function does not throw
3503 if the given key @a key was not found.
3504
3505 @param[in] ptr a JSON pointer to the element to access
3506 @param[in] default_value the value to return if @a ptr found no value
3507
3508 @tparam ValueType type compatible to JSON values, for instance `int` for
3509 JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
3510 JSON arrays. Note the type of the expected value at @a key and the default
3511 value @a default_value must be compatible.
3512
3513 @return copy of the element at key @a key or @a default_value if @a key
3514 is not found
3515
3516 @throw type_error.302 if @a default_value does not match the type of the
3517 value at @a ptr
3518 @throw type_error.306 if the JSON value is not an object; in that case,
3519 using `value()` with a key makes no sense.
3520
3521 @complexity Logarithmic in the size of the container.
3522
3523 @liveexample{The example below shows how object elements can be queried
3524 with a default value.,basic_json__value_ptr}
3525
3526 @sa @ref operator[](const json_pointer&) for unchecked access by reference
3527
3528 @since version 2.0.2
3529 */
3530 template<class ValueType, typename std::enable_if<
3531 std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0>
3532 ValueType value(const json_pointer& ptr, const ValueType& default_value) const
3533 {
3534 // at only works for objects
3535 if (JSON_HEDLEY_LIKELY(is_object()))
3536 {
3537 // if pointer resolves a value, return it or use default value
3538 JSON_TRY
3539 {
3540 return ptr.get_checked(this);
3541 }
3542 JSON_INTERNAL_CATCH (out_of_range&)
3543 {
3544 return default_value;
3545 }
3546 }
3547
3548 JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name())));
3549 }
3550
3551 /*!
3552 @brief overload for a default value of type const char*
3553 @copydoc basic_json::value(const json_pointer&, ValueType) const
3554 */
3555 JSON_HEDLEY_NON_NULL(3)
3556 string_t value(const json_pointer& ptr, const char* default_value) const
3557 {
3558 return value(ptr, string_t(default_value));
3559 }
3560
3561 /*!
3562 @brief access the first element
3563
3564 Returns a reference to the first element in the container. For a JSON
3565 container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
3566
3567 @return In case of a structured type (array or object), a reference to the
3568 first element is returned. In case of number, string, or boolean values, a
3569 reference to the value is returned.
3570
3571 @complexity Constant.
3572
3573 @pre The JSON value must not be `null` (would throw `std::out_of_range`)
3574 or an empty array or object (undefined behavior, **guarded by
3575 assertions**).
3576 @post The JSON value remains unchanged.
3577
3578 @throw invalid_iterator.214 when called on `null` value
3579
3580 @liveexample{The following code shows an example for `front()`.,front}
3581
3582 @sa @ref back() -- access the last element
3583
3584 @since version 1.0.0
3585 */
3586 reference front()
3587 {
3588 return *begin();
3589 }
3590
3591 /*!
3592 @copydoc basic_json::front()
3593 */
3594 const_reference front() const
3595 {
3596 return *cbegin();
3597 }
3598
3599 /*!
3600 @brief access the last element
3601
3602 Returns a reference to the last element in the container. For a JSON
3603 container `c`, the expression `c.back()` is equivalent to
3604 @code {.cpp}
3605 auto tmp = c.end();
3606 --tmp;
3607 return *tmp;
3608 @endcode
3609
3610 @return In case of a structured type (array or object), a reference to the
3611 last element is returned. In case of number, string, or boolean values, a
3612 reference to the value is returned.
3613
3614 @complexity Constant.
3615
3616 @pre The JSON value must not be `null` (would throw `std::out_of_range`)
3617 or an empty array or object (undefined behavior, **guarded by
3618 assertions**).
3619 @post The JSON value remains unchanged.
3620
3621 @throw invalid_iterator.214 when called on a `null` value. See example
3622 below.
3623
3624 @liveexample{The following code shows an example for `back()`.,back}
3625
3626 @sa @ref front() -- access the first element
3627
3628 @since version 1.0.0
3629 */
3630 reference back()
3631 {
3632 auto tmp = end();
3633 --tmp;
3634 return *tmp;
3635 }
3636
3637 /*!
3638 @copydoc basic_json::back()
3639 */
3640 const_reference back() const
3641 {
3642 auto tmp = cend();
3643 --tmp;
3644 return *tmp;
3645 }
3646
3647 /*!
3648 @brief remove element given an iterator
3649
3650 Removes the element specified by iterator @a pos. The iterator @a pos must
3651 be valid and dereferenceable. Thus the `end()` iterator (which is valid,
3652 but is not dereferenceable) cannot be used as a value for @a pos.
3653
3654 If called on a primitive type other than `null`, the resulting JSON value
3655 will be `null`.
3656
3657 @param[in] pos iterator to the element to remove
3658 @return Iterator following the last removed element. If the iterator @a
3659 pos refers to the last element, the `end()` iterator is returned.
3660
3661 @tparam IteratorType an @ref iterator or @ref const_iterator
3662
3663 @post Invalidates iterators and references at or after the point of the
3664 erase, including the `end()` iterator.
3665
3666 @throw type_error.307 if called on a `null` value; example: `"cannot use
3667 erase() with null"`
3668 @throw invalid_iterator.202 if called on an iterator which does not belong
3669 to the current JSON value; example: `"iterator does not fit current
3670 value"`
3671 @throw invalid_iterator.205 if called on a primitive type with invalid
3672 iterator (i.e., any iterator which is not `begin()`); example: `"iterator
3673 out of range"`
3674
3675 @complexity The complexity depends on the type:
3676 - objects: amortized constant
3677 - arrays: linear in distance between @a pos and the end of the container
3678 - strings: linear in the length of the string
3679 - other types: constant
3680
3681 @liveexample{The example shows the result of `erase()` for different JSON
3682 types.,erase__IteratorType}
3683
3684 @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
3685 the given range
3686 @sa @ref erase(const typename object_t::key_type&) -- removes the element
3687 from an object at the given key
3688 @sa @ref erase(const size_type) -- removes the element from an array at
3689 the given index
3690
3691 @since version 1.0.0
3692 */
3693 template<class IteratorType, typename std::enable_if<
3694 std::is_same<IteratorType, typename basic_json_t::iterator>::value or
3695 std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
3696 = 0>
3697 IteratorType erase(IteratorType pos)
3698 {
3699 // make sure iterator fits the current value
3700 if (JSON_HEDLEY_UNLIKELY(this != pos.m_object))
3701 {
3702 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
3703 }
3704
3705 IteratorType result = end();
3706
3707 switch (m_type)
3708 {
3709 case value_t::boolean:
3710 case value_t::number_float:
3711 case value_t::number_integer:
3712 case value_t::number_unsigned:
3713 case value_t::string:
3714 {
3715 if (JSON_HEDLEY_UNLIKELY(not pos.m_it.primitive_iterator.is_begin()))
3716 {
3717 JSON_THROW(invalid_iterator::create(205, "iterator out of range"));
3718 }
3719
3720 if (is_string())
3721 {
3722 AllocatorType<string_t> alloc;
3723 std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
3724 std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
3725 m_value.string = nullptr;
3726 }
3727
3728 m_type = value_t::null;
3729 assert_invariant();
3730 break;
3731 }
3732
3733 case value_t::object:
3734 {
3735 result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
3736 break;
3737 }
3738
3739 case value_t::array:
3740 {
3741 result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
3742 break;
3743 }
3744
3745 default:
3746 JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
3747 }
3748
3749 return result;
3750 }
3751
3752 /*!
3753 @brief remove elements given an iterator range
3754
3755 Removes the element specified by the range `[first; last)`. The iterator
3756 @a first does not need to be dereferenceable if `first == last`: erasing
3757 an empty range is a no-op.
3758
3759 If called on a primitive type other than `null`, the resulting JSON value
3760 will be `null`.
3761
3762 @param[in] first iterator to the beginning of the range to remove
3763 @param[in] last iterator past the end of the range to remove
3764 @return Iterator following the last removed element. If the iterator @a
3765 second refers to the last element, the `end()` iterator is returned.
3766
3767 @tparam IteratorType an @ref iterator or @ref const_iterator
3768
3769 @post Invalidates iterators and references at or after the point of the
3770 erase, including the `end()` iterator.
3771
3772 @throw type_error.307 if called on a `null` value; example: `"cannot use
3773 erase() with null"`
3774 @throw invalid_iterator.203 if called on iterators which does not belong
3775 to the current JSON value; example: `"iterators do not fit current value"`
3776 @throw invalid_iterator.204 if called on a primitive type with invalid
3777 iterators (i.e., if `first != begin()` and `last != end()`); example:
3778 `"iterators out of range"`
3779
3780 @complexity The complexity depends on the type:
3781 - objects: `log(size()) + std::distance(first, last)`
3782 - arrays: linear in the distance between @a first and @a last, plus linear
3783 in the distance between @a last and end of the container
3784 - strings: linear in the length of the string
3785 - other types: constant
3786
3787 @liveexample{The example shows the result of `erase()` for different JSON
3788 types.,erase__IteratorType_IteratorType}
3789
3790 @sa @ref erase(IteratorType) -- removes the element at a given position
3791 @sa @ref erase(const typename object_t::key_type&) -- removes the element
3792 from an object at the given key
3793 @sa @ref erase(const size_type) -- removes the element from an array at
3794 the given index
3795
3796 @since version 1.0.0
3797 */
3798 template<class IteratorType, typename std::enable_if<
3799 std::is_same<IteratorType, typename basic_json_t::iterator>::value or
3800 std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type
3801 = 0>
3802 IteratorType erase(IteratorType first, IteratorType last)
3803 {
3804 // make sure iterator fits the current value
3805 if (JSON_HEDLEY_UNLIKELY(this != first.m_object or this != last.m_object))
3806 {
3807 JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value"));
3808 }
3809
3810 IteratorType result = end();
3811
3812 switch (m_type)
3813 {
3814 case value_t::boolean:
3815 case value_t::number_float:
3816 case value_t::number_integer:
3817 case value_t::number_unsigned:
3818 case value_t::string:
3819 {
3820 if (JSON_HEDLEY_LIKELY(not first.m_it.primitive_iterator.is_begin()
3821 or not last.m_it.primitive_iterator.is_end()))
3822 {
3823 JSON_THROW(invalid_iterator::create(204, "iterators out of range"));
3824 }
3825
3826 if (is_string())
3827 {
3828 AllocatorType<string_t> alloc;
3829 std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string);
3830 std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1);
3831 m_value.string = nullptr;
3832 }
3833
3834 m_type = value_t::null;
3835 assert_invariant();
3836 break;
3837 }
3838
3839 case value_t::object:
3840 {
3841 result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
3842 last.m_it.object_iterator);
3843 break;
3844 }
3845
3846 case value_t::array:
3847 {
3848 result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
3849 last.m_it.array_iterator);
3850 break;
3851 }
3852
3853 default:
3854 JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
3855 }
3856
3857 return result;
3858 }
3859
3860 /*!
3861 @brief remove element from a JSON object given a key
3862
3863 Removes elements from a JSON object with the key value @a key.
3864
3865 @param[in] key value of the elements to remove
3866
3867 @return Number of elements removed. If @a ObjectType is the default
3868 `std::map` type, the return value will always be `0` (@a key was not
3869 found) or `1` (@a key was found).
3870
3871 @post References and iterators to the erased elements are invalidated.
3872 Other references and iterators are not affected.
3873
3874 @throw type_error.307 when called on a type other than JSON object;
3875 example: `"cannot use erase() with null"`
3876
3877 @complexity `log(size()) + count(key)`
3878
3879 @liveexample{The example shows the effect of `erase()`.,erase__key_type}
3880
3881 @sa @ref erase(IteratorType) -- removes the element at a given position
3882 @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
3883 the given range
3884 @sa @ref erase(const size_type) -- removes the element from an array at
3885 the given index
3886
3887 @since version 1.0.0
3888 */
3889 size_type erase(const typename object_t::key_type& key)
3890 {
3891 // this erase only works for objects
3892 if (JSON_HEDLEY_LIKELY(is_object()))
3893 {
3894 return m_value.object->erase(key);
3895 }
3896
3897 JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
3898 }
3899
3900 /*!
3901 @brief remove element from a JSON array given an index
3902
3903 Removes element from a JSON array at the index @a idx.
3904
3905 @param[in] idx index of the element to remove
3906
3907 @throw type_error.307 when called on a type other than JSON object;
3908 example: `"cannot use erase() with null"`
3909 @throw out_of_range.401 when `idx >= size()`; example: `"array index 17
3910 is out of range"`
3911
3912 @complexity Linear in distance between @a idx and the end of the container.
3913
3914 @liveexample{The example shows the effect of `erase()`.,erase__size_type}
3915
3916 @sa @ref erase(IteratorType) -- removes the element at a given position
3917 @sa @ref erase(IteratorType, IteratorType) -- removes the elements in
3918 the given range
3919 @sa @ref erase(const typename object_t::key_type&) -- removes the element
3920 from an object at the given key
3921
3922 @since version 1.0.0
3923 */
3924 void erase(const size_type idx)
3925 {
3926 // this erase only works for arrays
3927 if (JSON_HEDLEY_LIKELY(is_array()))
3928 {
3929 if (JSON_HEDLEY_UNLIKELY(idx >= size()))
3930 {
3931 JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
3932 }
3933
3934 m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
3935 }
3936 else
3937 {
3938 JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name())));
3939 }
3940 }
3941
3942 /// @}
3943
3944
3945 ////////////
3946 // lookup //
3947 ////////////
3948
3949 /// @name lookup
3950 /// @{
3951
3952 /*!
3953 @brief find an element in a JSON object
3954
3955 Finds an element in a JSON object with key equivalent to @a key. If the
3956 element is not found or the JSON value is not an object, end() is
3957 returned.
3958
3959 @note This method always returns @ref end() when executed on a JSON type
3960 that is not an object.
3961
3962 @param[in] key key value of the element to search for.
3963
3964 @return Iterator to an element with key equivalent to @a key. If no such
3965 element is found or the JSON value is not an object, past-the-end (see
3966 @ref end()) iterator is returned.
3967
3968 @complexity Logarithmic in the size of the JSON object.
3969
3970 @liveexample{The example shows how `find()` is used.,find__key_type}
3971
3972 @sa @ref contains(KeyT&&) const -- checks whether a key exists
3973
3974 @since version 1.0.0
3975 */
3976 template<typename KeyT>
3977 iterator find(KeyT&& key)
3978 {
3979 auto result = end();
3980
3981 if (is_object())
3982 {
3983 result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
3984 }
3985
3986 return result;
3987 }
3988
3989 /*!
3990 @brief find an element in a JSON object
3991 @copydoc find(KeyT&&)
3992 */
3993 template<typename KeyT>
3994 const_iterator find(KeyT&& key) const
3995 {
3996 auto result = cend();
3997
3998 if (is_object())
3999 {
4000 result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key));
4001 }
4002
4003 return result;
4004 }
4005
4006 /*!
4007 @brief returns the number of occurrences of a key in a JSON object
4008
4009 Returns the number of elements with key @a key. If ObjectType is the
4010 default `std::map` type, the return value will always be `0` (@a key was
4011 not found) or `1` (@a key was found).
4012
4013 @note This method always returns `0` when executed on a JSON type that is
4014 not an object.
4015
4016 @param[in] key key value of the element to count
4017
4018 @return Number of elements with key @a key. If the JSON value is not an
4019 object, the return value will be `0`.
4020
4021 @complexity Logarithmic in the size of the JSON object.
4022
4023 @liveexample{The example shows how `count()` is used.,count}
4024
4025 @since version 1.0.0
4026 */
4027 template<typename KeyT>
4028 size_type count(KeyT&& key) const
4029 {
4030 // return 0 for all nonobject types
4031 return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0;
4032 }
4033
4034 /*!
4035 @brief check the existence of an element in a JSON object
4036
4037 Check whether an element exists in a JSON object with key equivalent to
4038 @a key. If the element is not found or the JSON value is not an object,
4039 false is returned.
4040
4041 @note This method always returns false when executed on a JSON type
4042 that is not an object.
4043
4044 @param[in] key key value to check its existence.
4045
4046 @return true if an element with specified @a key exists. If no such
4047 element with such key is found or the JSON value is not an object,
4048 false is returned.
4049
4050 @complexity Logarithmic in the size of the JSON object.
4051
4052 @liveexample{The following code shows an example for `contains()`.,contains}
4053
4054 @sa @ref find(KeyT&&) -- returns an iterator to an object element
4055 @sa @ref contains(const json_pointer&) const -- checks the existence for a JSON pointer
4056
4057 @since version 3.6.0
4058 */
4059 template<typename KeyT, typename std::enable_if<
4060 not std::is_same<typename std::decay<KeyT>::type, json_pointer>::value, int>::type = 0>
4061 bool contains(KeyT && key) const
4062 {
4063 return is_object() and m_value.object->find(std::forward<KeyT>(key)) != m_value.object->end();
4064 }
4065
4066 /*!
4067 @brief check the existence of an element in a JSON object given a JSON pointer
4068
4069 Check whether the given JSON pointer @a ptr can be resolved in the current
4070 JSON value.
4071
4072 @note This method can be executed on any JSON value type.
4073
4074 @param[in] ptr JSON pointer to check its existence.
4075
4076 @return true if the JSON pointer can be resolved to a stored value, false
4077 otherwise.
4078
4079 @post If `j.contains(ptr)` returns true, it is safe to call `j[ptr]`.
4080
4081 @throw parse_error.106 if an array index begins with '0'
4082 @throw parse_error.109 if an array index was not a number
4083
4084 @complexity Logarithmic in the size of the JSON object.
4085
4086 @liveexample{The following code shows an example for `contains()`.,contains_json_pointer}
4087
4088 @sa @ref contains(KeyT &&) const -- checks the existence of a key
4089
4090 @since version 3.7.0
4091 */
4092 bool contains(const json_pointer& ptr) const
4093 {
4094 return ptr.contains(this);
4095 }
4096
4097 /// @}
4098
4099
4100 ///////////////
4101 // iterators //
4102 ///////////////
4103
4104 /// @name iterators
4105 /// @{
4106
4107 /*!
4108 @brief returns an iterator to the first element
4109
4110 Returns an iterator to the first element.
4111
4112 @image html range-begin-end.svg "Illustration from cppreference.com"
4113
4114 @return iterator to the first element
4115
4116 @complexity Constant.
4117
4118 @requirement This function helps `basic_json` satisfying the
4119 [Container](https://en.cppreference.com/w/cpp/named_req/Container)
4120 requirements:
4121 - The complexity is constant.
4122
4123 @liveexample{The following code shows an example for `begin()`.,begin}
4124
4125 @sa @ref cbegin() -- returns a const iterator to the beginning
4126 @sa @ref end() -- returns an iterator to the end
4127 @sa @ref cend() -- returns a const iterator to the end
4128
4129 @since version 1.0.0
4130 */
4131 iterator begin() noexcept
4132 {
4133 iterator result(this);
4134 result.set_begin();
4135 return result;
4136 }
4137
4138 /*!
4139 @copydoc basic_json::cbegin()
4140 */
4141 const_iterator begin() const noexcept
4142 {
4143 return cbegin();
4144 }
4145
4146 /*!
4147 @brief returns a const iterator to the first element
4148
4149 Returns a const iterator to the first element.
4150
4151 @image html range-begin-end.svg "Illustration from cppreference.com"
4152
4153 @return const iterator to the first element
4154
4155 @complexity Constant.
4156
4157 @requirement This function helps `basic_json` satisfying the
4158 [Container](https://en.cppreference.com/w/cpp/named_req/Container)
4159 requirements:
4160 - The complexity is constant.
4161 - Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
4162
4163 @liveexample{The following code shows an example for `cbegin()`.,cbegin}
4164
4165 @sa @ref begin() -- returns an iterator to the beginning
4166 @sa @ref end() -- returns an iterator to the end
4167 @sa @ref cend() -- returns a const iterator to the end
4168
4169 @since version 1.0.0
4170 */
4171 const_iterator cbegin() const noexcept
4172 {
4173 const_iterator result(this);
4174 result.set_begin();
4175 return result;
4176 }
4177
4178 /*!
4179 @brief returns an iterator to one past the last element
4180
4181 Returns an iterator to one past the last element.
4182
4183 @image html range-begin-end.svg "Illustration from cppreference.com"
4184
4185 @return iterator one past the last element
4186
4187 @complexity Constant.
4188
4189 @requirement This function helps `basic_json` satisfying the
4190 [Container](https://en.cppreference.com/w/cpp/named_req/Container)
4191 requirements:
4192 - The complexity is constant.
4193
4194 @liveexample{The following code shows an example for `end()`.,end}
4195
4196 @sa @ref cend() -- returns a const iterator to the end
4197 @sa @ref begin() -- returns an iterator to the beginning
4198 @sa @ref cbegin() -- returns a const iterator to the beginning
4199
4200 @since version 1.0.0
4201 */
4202 iterator end() noexcept
4203 {
4204 iterator result(this);
4205 result.set_end();
4206 return result;
4207 }
4208
4209 /*!
4210 @copydoc basic_json::cend()
4211 */
4212 const_iterator end() const noexcept
4213 {
4214 return cend();
4215 }
4216
4217 /*!
4218 @brief returns a const iterator to one past the last element
4219
4220 Returns a const iterator to one past the last element.
4221
4222 @image html range-begin-end.svg "Illustration from cppreference.com"
4223
4224 @return const iterator one past the last element
4225
4226 @complexity Constant.
4227
4228 @requirement This function helps `basic_json` satisfying the
4229 [Container](https://en.cppreference.com/w/cpp/named_req/Container)
4230 requirements:
4231 - The complexity is constant.
4232 - Has the semantics of `const_cast<const basic_json&>(*this).end()`.
4233
4234 @liveexample{The following code shows an example for `cend()`.,cend}
4235
4236 @sa @ref end() -- returns an iterator to the end
4237 @sa @ref begin() -- returns an iterator to the beginning
4238 @sa @ref cbegin() -- returns a const iterator to the beginning
4239
4240 @since version 1.0.0
4241 */
4242 const_iterator cend() const noexcept
4243 {
4244 const_iterator result(this);
4245 result.set_end();
4246 return result;
4247 }
4248
4249 /*!
4250 @brief returns an iterator to the reverse-beginning
4251
4252 Returns an iterator to the reverse-beginning; that is, the last element.
4253
4254 @image html range-rbegin-rend.svg "Illustration from cppreference.com"
4255
4256 @complexity Constant.
4257
4258 @requirement This function helps `basic_json` satisfying the
4259 [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
4260 requirements:
4261 - The complexity is constant.
4262 - Has the semantics of `reverse_iterator(end())`.
4263
4264 @liveexample{The following code shows an example for `rbegin()`.,rbegin}
4265
4266 @sa @ref crbegin() -- returns a const reverse iterator to the beginning
4267 @sa @ref rend() -- returns a reverse iterator to the end
4268 @sa @ref crend() -- returns a const reverse iterator to the end
4269
4270 @since version 1.0.0
4271 */
4272 reverse_iterator rbegin() noexcept
4273 {
4274 return reverse_iterator(end());
4275 }
4276
4277 /*!
4278 @copydoc basic_json::crbegin()
4279 */
4280 const_reverse_iterator rbegin() const noexcept
4281 {
4282 return crbegin();
4283 }
4284
4285 /*!
4286 @brief returns an iterator to the reverse-end
4287
4288 Returns an iterator to the reverse-end; that is, one before the first
4289 element.
4290
4291 @image html range-rbegin-rend.svg "Illustration from cppreference.com"
4292
4293 @complexity Constant.
4294
4295 @requirement This function helps `basic_json` satisfying the
4296 [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
4297 requirements:
4298 - The complexity is constant.
4299 - Has the semantics of `reverse_iterator(begin())`.
4300
4301 @liveexample{The following code shows an example for `rend()`.,rend}
4302
4303 @sa @ref crend() -- returns a const reverse iterator to the end
4304 @sa @ref rbegin() -- returns a reverse iterator to the beginning
4305 @sa @ref crbegin() -- returns a const reverse iterator to the beginning
4306
4307 @since version 1.0.0
4308 */
4309 reverse_iterator rend() noexcept
4310 {
4311 return reverse_iterator(begin());
4312 }
4313
4314 /*!
4315 @copydoc basic_json::crend()
4316 */
4317 const_reverse_iterator rend() const noexcept
4318 {
4319 return crend();
4320 }
4321
4322 /*!
4323 @brief returns a const reverse iterator to the last element
4324
4325 Returns a const iterator to the reverse-beginning; that is, the last
4326 element.
4327
4328 @image html range-rbegin-rend.svg "Illustration from cppreference.com"
4329
4330 @complexity Constant.
4331
4332 @requirement This function helps `basic_json` satisfying the
4333 [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
4334 requirements:
4335 - The complexity is constant.
4336 - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
4337
4338 @liveexample{The following code shows an example for `crbegin()`.,crbegin}
4339
4340 @sa @ref rbegin() -- returns a reverse iterator to the beginning
4341 @sa @ref rend() -- returns a reverse iterator to the end
4342 @sa @ref crend() -- returns a const reverse iterator to the end
4343
4344 @since version 1.0.0
4345 */
4346 const_reverse_iterator crbegin() const noexcept
4347 {
4348 return const_reverse_iterator(cend());
4349 }
4350
4351 /*!
4352 @brief returns a const reverse iterator to one before the first
4353
4354 Returns a const reverse iterator to the reverse-end; that is, one before
4355 the first element.
4356
4357 @image html range-rbegin-rend.svg "Illustration from cppreference.com"
4358
4359 @complexity Constant.
4360
4361 @requirement This function helps `basic_json` satisfying the
4362 [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer)
4363 requirements:
4364 - The complexity is constant.
4365 - Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
4366
4367 @liveexample{The following code shows an example for `crend()`.,crend}
4368
4369 @sa @ref rend() -- returns a reverse iterator to the end
4370 @sa @ref rbegin() -- returns a reverse iterator to the beginning
4371 @sa @ref crbegin() -- returns a const reverse iterator to the beginning
4372
4373 @since version 1.0.0
4374 */
4375 const_reverse_iterator crend() const noexcept
4376 {
4377 return const_reverse_iterator(cbegin());
4378 }
4379
4380 public:
4381 /*!
4382 @brief wrapper to access iterator member functions in range-based for
4383
4384 This function allows to access @ref iterator::key() and @ref
4385 iterator::value() during range-based for loops. In these loops, a
4386 reference to the JSON values is returned, so there is no access to the
4387 underlying iterator.
4388
4389 For loop without iterator_wrapper:
4390
4391 @code{cpp}
4392 for (auto it = j_object.begin(); it != j_object.end(); ++it)
4393 {
4394 std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
4395 }
4396 @endcode
4397
4398 Range-based for loop without iterator proxy:
4399
4400 @code{cpp}
4401 for (auto it : j_object)
4402 {
4403 // "it" is of type json::reference and has no key() member
4404 std::cout << "value: " << it << '\n';
4405 }
4406 @endcode
4407
4408 Range-based for loop with iterator proxy:
4409
4410 @code{cpp}
4411 for (auto it : json::iterator_wrapper(j_object))
4412 {
4413 std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
4414 }
4415 @endcode
4416
4417 @note When iterating over an array, `key()` will return the index of the
4418 element as string (see example).
4419
4420 @param[in] ref reference to a JSON value
4421 @return iteration proxy object wrapping @a ref with an interface to use in
4422 range-based for loops
4423
4424 @liveexample{The following code shows how the wrapper is used,iterator_wrapper}
4425
4426 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
4427 changes in the JSON value.
4428
4429 @complexity Constant.
4430
4431 @note The name of this function is not yet final and may change in the
4432 future.
4433
4434 @deprecated This stream operator is deprecated and will be removed in
4435 future 4.0.0 of the library. Please use @ref items() instead;
4436 that is, replace `json::iterator_wrapper(j)` with `j.items()`.
4437 */
4438 JSON_HEDLEY_DEPRECATED(3.1.0)
4439 static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept
4440 {
4441 return ref.items();
4442 }
4443
4444 /*!
4445 @copydoc iterator_wrapper(reference)
4446 */
4447 JSON_HEDLEY_DEPRECATED(3.1.0)
4448 static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept
4449 {
4450 return ref.items();
4451 }
4452
4453 /*!
4454 @brief helper to access iterator member functions in range-based for
4455
4456 This function allows to access @ref iterator::key() and @ref
4457 iterator::value() during range-based for loops. In these loops, a
4458 reference to the JSON values is returned, so there is no access to the
4459 underlying iterator.
4460
4461 For loop without `items()` function:
4462
4463 @code{cpp}
4464 for (auto it = j_object.begin(); it != j_object.end(); ++it)
4465 {
4466 std::cout << "key: " << it.key() << ", value:" << it.value() << '\n';
4467 }
4468 @endcode
4469
4470 Range-based for loop without `items()` function:
4471
4472 @code{cpp}
4473 for (auto it : j_object)
4474 {
4475 // "it" is of type json::reference and has no key() member
4476 std::cout << "value: " << it << '\n';
4477 }
4478 @endcode
4479
4480 Range-based for loop with `items()` function:
4481
4482 @code{cpp}
4483 for (auto& el : j_object.items())
4484 {
4485 std::cout << "key: " << el.key() << ", value:" << el.value() << '\n';
4486 }
4487 @endcode
4488
4489 The `items()` function also allows to use
4490 [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding)
4491 (C++17):
4492
4493 @code{cpp}
4494 for (auto& [key, val] : j_object.items())
4495 {
4496 std::cout << "key: " << key << ", value:" << val << '\n';
4497 }
4498 @endcode
4499
4500 @note When iterating over an array, `key()` will return the index of the
4501 element as string (see example). For primitive types (e.g., numbers),
4502 `key()` returns an empty string.
4503
4504 @return iteration proxy object wrapping @a ref with an interface to use in
4505 range-based for loops
4506
4507 @liveexample{The following code shows how the function is used.,items}
4508
4509 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
4510 changes in the JSON value.
4511
4512 @complexity Constant.
4513
4514 @since version 3.1.0, structured bindings support since 3.5.0.
4515 */
4516 iteration_proxy<iterator> items() noexcept
4517 {
4518 return iteration_proxy<iterator>(*this);
4519 }
4520
4521 /*!
4522 @copydoc items()
4523 */
4524 iteration_proxy<const_iterator> items() const noexcept
4525 {
4526 return iteration_proxy<const_iterator>(*this);
4527 }
4528
4529 /// @}
4530
4531
4532 //////////////
4533 // capacity //
4534 //////////////
4535
4536 /// @name capacity
4537 /// @{
4538
4539 /*!
4540 @brief checks whether the container is empty.
4541
4542 Checks if a JSON value has no elements (i.e. whether its @ref size is `0`).
4543
4544 @return The return value depends on the different types and is
4545 defined as follows:
4546 Value type | return value
4547 ----------- | -------------
4548 null | `true`
4549 boolean | `false`
4550 string | `false`
4551 number | `false`
4552 object | result of function `object_t::empty()`
4553 array | result of function `array_t::empty()`
4554
4555 @liveexample{The following code uses `empty()` to check if a JSON
4556 object contains any elements.,empty}
4557
4558 @complexity Constant, as long as @ref array_t and @ref object_t satisfy
4559 the Container concept; that is, their `empty()` functions have constant
4560 complexity.
4561
4562 @iterators No changes.
4563
4564 @exceptionsafety No-throw guarantee: this function never throws exceptions.
4565
4566 @note This function does not return whether a string stored as JSON value
4567 is empty - it returns whether the JSON container itself is empty which is
4568 false in the case of a string.
4569
4570 @requirement This function helps `basic_json` satisfying the
4571 [Container](https://en.cppreference.com/w/cpp/named_req/Container)
4572 requirements:
4573 - The complexity is constant.
4574 - Has the semantics of `begin() == end()`.
4575
4576 @sa @ref size() -- returns the number of elements
4577
4578 @since version 1.0.0
4579 */
4580 bool empty() const noexcept
4581 {
4582 switch (m_type)
4583 {
4584 case value_t::null:
4585 {
4586 // null values are empty
4587 return true;
4588 }
4589
4590 case value_t::array:
4591 {
4592 // delegate call to array_t::empty()
4593 return m_value.array->empty();
4594 }
4595
4596 case value_t::object:
4597 {
4598 // delegate call to object_t::empty()
4599 return m_value.object->empty();
4600 }
4601
4602 default:
4603 {
4604 // all other types are nonempty
4605 return false;
4606 }
4607 }
4608 }
4609
4610 /*!
4611 @brief returns the number of elements
4612
4613 Returns the number of elements in a JSON value.
4614
4615 @return The return value depends on the different types and is
4616 defined as follows:
4617 Value type | return value
4618 ----------- | -------------
4619 null | `0`
4620 boolean | `1`
4621 string | `1`
4622 number | `1`
4623 object | result of function object_t::size()
4624 array | result of function array_t::size()
4625
4626 @liveexample{The following code calls `size()` on the different value
4627 types.,size}
4628
4629 @complexity Constant, as long as @ref array_t and @ref object_t satisfy
4630 the Container concept; that is, their size() functions have constant
4631 complexity.
4632
4633 @iterators No changes.
4634
4635 @exceptionsafety No-throw guarantee: this function never throws exceptions.
4636
4637 @note This function does not return the length of a string stored as JSON
4638 value - it returns the number of elements in the JSON value which is 1 in
4639 the case of a string.
4640
4641 @requirement This function helps `basic_json` satisfying the
4642 [Container](https://en.cppreference.com/w/cpp/named_req/Container)
4643 requirements:
4644 - The complexity is constant.
4645 - Has the semantics of `std::distance(begin(), end())`.
4646
4647 @sa @ref empty() -- checks whether the container is empty
4648 @sa @ref max_size() -- returns the maximal number of elements
4649
4650 @since version 1.0.0
4651 */
4652 size_type size() const noexcept
4653 {
4654 switch (m_type)
4655 {
4656 case value_t::null:
4657 {
4658 // null values are empty
4659 return 0;
4660 }
4661
4662 case value_t::array:
4663 {
4664 // delegate call to array_t::size()
4665 return m_value.array->size();
4666 }
4667
4668 case value_t::object:
4669 {
4670 // delegate call to object_t::size()
4671 return m_value.object->size();
4672 }
4673
4674 default:
4675 {
4676 // all other types have size 1
4677 return 1;
4678 }
4679 }
4680 }
4681
4682 /*!
4683 @brief returns the maximum possible number of elements
4684
4685 Returns the maximum number of elements a JSON value is able to hold due to
4686 system or library implementation limitations, i.e. `std::distance(begin(),
4687 end())` for the JSON value.
4688
4689 @return The return value depends on the different types and is
4690 defined as follows:
4691 Value type | return value
4692 ----------- | -------------
4693 null | `0` (same as `size()`)
4694 boolean | `1` (same as `size()`)
4695 string | `1` (same as `size()`)
4696 number | `1` (same as `size()`)
4697 object | result of function `object_t::max_size()`
4698 array | result of function `array_t::max_size()`
4699
4700 @liveexample{The following code calls `max_size()` on the different value
4701 types. Note the output is implementation specific.,max_size}
4702
4703 @complexity Constant, as long as @ref array_t and @ref object_t satisfy
4704 the Container concept; that is, their `max_size()` functions have constant
4705 complexity.
4706
4707 @iterators No changes.
4708
4709 @exceptionsafety No-throw guarantee: this function never throws exceptions.
4710
4711 @requirement This function helps `basic_json` satisfying the
4712 [Container](https://en.cppreference.com/w/cpp/named_req/Container)
4713 requirements:
4714 - The complexity is constant.
4715 - Has the semantics of returning `b.size()` where `b` is the largest
4716 possible JSON value.
4717
4718 @sa @ref size() -- returns the number of elements
4719
4720 @since version 1.0.0
4721 */
4722 size_type max_size() const noexcept
4723 {
4724 switch (m_type)
4725 {
4726 case value_t::array:
4727 {
4728 // delegate call to array_t::max_size()
4729 return m_value.array->max_size();
4730 }
4731
4732 case value_t::object:
4733 {
4734 // delegate call to object_t::max_size()
4735 return m_value.object->max_size();
4736 }
4737
4738 default:
4739 {
4740 // all other types have max_size() == size()
4741 return size();
4742 }
4743 }
4744 }
4745
4746 /// @}
4747
4748
4749 ///////////////
4750 // modifiers //
4751 ///////////////
4752
4753 /// @name modifiers
4754 /// @{
4755
4756 /*!
4757 @brief clears the contents
4758
4759 Clears the content of a JSON value and resets it to the default value as
4760 if @ref basic_json(value_t) would have been called with the current value
4761 type from @ref type():
4762
4763 Value type | initial value
4764 ----------- | -------------
4765 null | `null`
4766 boolean | `false`
4767 string | `""`
4768 number | `0`
4769 object | `{}`
4770 array | `[]`
4771
4772 @post Has the same effect as calling
4773 @code {.cpp}
4774 *this = basic_json(type());
4775 @endcode
4776
4777 @liveexample{The example below shows the effect of `clear()` to different
4778 JSON types.,clear}
4779
4780 @complexity Linear in the size of the JSON value.
4781
4782 @iterators All iterators, pointers and references related to this container
4783 are invalidated.
4784
4785 @exceptionsafety No-throw guarantee: this function never throws exceptions.
4786
4787 @sa @ref basic_json(value_t) -- constructor that creates an object with the
4788 same value than calling `clear()`
4789
4790 @since version 1.0.0
4791 */
4792 void clear() noexcept
4793 {
4794 switch (m_type)
4795 {
4796 case value_t::number_integer:
4797 {
4798 m_value.number_integer = 0;
4799 break;
4800 }
4801
4802 case value_t::number_unsigned:
4803 {
4804 m_value.number_unsigned = 0;
4805 break;
4806 }
4807
4808 case value_t::number_float:
4809 {
4810 m_value.number_float = 0.0;
4811 break;
4812 }
4813
4814 case value_t::boolean:
4815 {
4816 m_value.boolean = false;
4817 break;
4818 }
4819
4820 case value_t::string:
4821 {
4822 m_value.string->clear();
4823 break;
4824 }
4825
4826 case value_t::array:
4827 {
4828 m_value.array->clear();
4829 break;
4830 }
4831
4832 case value_t::object:
4833 {
4834 m_value.object->clear();
4835 break;
4836 }
4837
4838 default:
4839 break;
4840 }
4841 }
4842
4843 /*!
4844 @brief add an object to an array
4845
4846 Appends the given element @a val to the end of the JSON value. If the
4847 function is called on a JSON null value, an empty array is created before
4848 appending @a val.
4849
4850 @param[in] val the value to add to the JSON array
4851
4852 @throw type_error.308 when called on a type other than JSON array or
4853 null; example: `"cannot use push_back() with number"`
4854
4855 @complexity Amortized constant.
4856
4857 @liveexample{The example shows how `push_back()` and `+=` can be used to
4858 add elements to a JSON array. Note how the `null` value was silently
4859 converted to a JSON array.,push_back}
4860
4861 @since version 1.0.0
4862 */
4863 void push_back(basic_json&& val)
4864 {
4865 // push_back only works for null objects or arrays
4866 if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
4867 {
4868 JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
4869 }
4870
4871 // transform null object into an array
4872 if (is_null())
4873 {
4874 m_type = value_t::array;
4875 m_value = value_t::array;
4876 assert_invariant();
4877 }
4878
4879 // add element to array (move semantics)
4880 m_value.array->push_back(std::move(val));
4881 // invalidate object: mark it null so we do not call the destructor
4882 // cppcheck-suppress accessMoved
4883 val.m_type = value_t::null;
4884 }
4885
4886 /*!
4887 @brief add an object to an array
4888 @copydoc push_back(basic_json&&)
4889 */
4890 reference operator+=(basic_json&& val)
4891 {
4892 push_back(std::move(val));
4893 return *this;
4894 }
4895
4896 /*!
4897 @brief add an object to an array
4898 @copydoc push_back(basic_json&&)
4899 */
4900 void push_back(const basic_json& val)
4901 {
4902 // push_back only works for null objects or arrays
4903 if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
4904 {
4905 JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
4906 }
4907
4908 // transform null object into an array
4909 if (is_null())
4910 {
4911 m_type = value_t::array;
4912 m_value = value_t::array;
4913 assert_invariant();
4914 }
4915
4916 // add element to array
4917 m_value.array->push_back(val);
4918 }
4919
4920 /*!
4921 @brief add an object to an array
4922 @copydoc push_back(basic_json&&)
4923 */
4924 reference operator+=(const basic_json& val)
4925 {
4926 push_back(val);
4927 return *this;
4928 }
4929
4930 /*!
4931 @brief add an object to an object
4932
4933 Inserts the given element @a val to the JSON object. If the function is
4934 called on a JSON null value, an empty object is created before inserting
4935 @a val.
4936
4937 @param[in] val the value to add to the JSON object
4938
4939 @throw type_error.308 when called on a type other than JSON object or
4940 null; example: `"cannot use push_back() with number"`
4941
4942 @complexity Logarithmic in the size of the container, O(log(`size()`)).
4943
4944 @liveexample{The example shows how `push_back()` and `+=` can be used to
4945 add elements to a JSON object. Note how the `null` value was silently
4946 converted to a JSON object.,push_back__object_t__value}
4947
4948 @since version 1.0.0
4949 */
4950 void push_back(const typename object_t::value_type& val)
4951 {
4952 // push_back only works for null objects or objects
4953 if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
4954 {
4955 JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name())));
4956 }
4957
4958 // transform null object into an object
4959 if (is_null())
4960 {
4961 m_type = value_t::object;
4962 m_value = value_t::object;
4963 assert_invariant();
4964 }
4965
4966 // add element to array
4967 m_value.object->insert(val);
4968 }
4969
4970 /*!
4971 @brief add an object to an object
4972 @copydoc push_back(const typename object_t::value_type&)
4973 */
4974 reference operator+=(const typename object_t::value_type& val)
4975 {
4976 push_back(val);
4977 return *this;
4978 }
4979
4980 /*!
4981 @brief add an object to an object
4982
4983 This function allows to use `push_back` with an initializer list. In case
4984
4985 1. the current value is an object,
4986 2. the initializer list @a init contains only two elements, and
4987 3. the first element of @a init is a string,
4988
4989 @a init is converted into an object element and added using
4990 @ref push_back(const typename object_t::value_type&). Otherwise, @a init
4991 is converted to a JSON value and added using @ref push_back(basic_json&&).
4992
4993 @param[in] init an initializer list
4994
4995 @complexity Linear in the size of the initializer list @a init.
4996
4997 @note This function is required to resolve an ambiguous overload error,
4998 because pairs like `{"key", "value"}` can be both interpreted as
4999 `object_t::value_type` or `std::initializer_list<basic_json>`, see
5000 https://github.com/nlohmann/json/issues/235 for more information.
5001
5002 @liveexample{The example shows how initializer lists are treated as
5003 objects when possible.,push_back__initializer_list}
5004 */
5005 void push_back(initializer_list_t init)
5006 {
5007 if (is_object() and init.size() == 2 and (*init.begin())->is_string())
5008 {
5009 basic_json&& key = init.begin()->moved_or_copied();
5010 push_back(typename object_t::value_type(
5011 std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied()));
5012 }
5013 else
5014 {
5015 push_back(basic_json(init));
5016 }
5017 }
5018
5019 /*!
5020 @brief add an object to an object
5021 @copydoc push_back(initializer_list_t)
5022 */
5023 reference operator+=(initializer_list_t init)
5024 {
5025 push_back(init);
5026 return *this;
5027 }
5028
5029 /*!
5030 @brief add an object to an array
5031
5032 Creates a JSON value from the passed parameters @a args to the end of the
5033 JSON value. If the function is called on a JSON null value, an empty array
5034 is created before appending the value created from @a args.
5035
5036 @param[in] args arguments to forward to a constructor of @ref basic_json
5037 @tparam Args compatible types to create a @ref basic_json object
5038
5039 @return reference to the inserted element
5040
5041 @throw type_error.311 when called on a type other than JSON array or
5042 null; example: `"cannot use emplace_back() with number"`
5043
5044 @complexity Amortized constant.
5045
5046 @liveexample{The example shows how `push_back()` can be used to add
5047 elements to a JSON array. Note how the `null` value was silently converted
5048 to a JSON array.,emplace_back}
5049
5050 @since version 2.0.8, returns reference since 3.7.0
5051 */
5052 template<class... Args>
5053 reference emplace_back(Args&& ... args)
5054 {
5055 // emplace_back only works for null objects or arrays
5056 if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_array())))
5057 {
5058 JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name())));
5059 }
5060
5061 // transform null object into an array
5062 if (is_null())
5063 {
5064 m_type = value_t::array;
5065 m_value = value_t::array;
5066 assert_invariant();
5067 }
5068
5069 // add element to array (perfect forwarding)
5070 #ifdef JSON_HAS_CPP_17
5071 return m_value.array->emplace_back(std::forward<Args>(args)...);
5072 #else
5073 m_value.array->emplace_back(std::forward<Args>(args)...);
5074 return m_value.array->back();
5075 #endif
5076 }
5077
5078 /*!
5079 @brief add an object to an object if key does not exist
5080
5081 Inserts a new element into a JSON object constructed in-place with the
5082 given @a args if there is no element with the key in the container. If the
5083 function is called on a JSON null value, an empty object is created before
5084 appending the value created from @a args.
5085
5086 @param[in] args arguments to forward to a constructor of @ref basic_json
5087 @tparam Args compatible types to create a @ref basic_json object
5088
5089 @return a pair consisting of an iterator to the inserted element, or the
5090 already-existing element if no insertion happened, and a bool
5091 denoting whether the insertion took place.
5092
5093 @throw type_error.311 when called on a type other than JSON object or
5094 null; example: `"cannot use emplace() with number"`
5095
5096 @complexity Logarithmic in the size of the container, O(log(`size()`)).
5097
5098 @liveexample{The example shows how `emplace()` can be used to add elements
5099 to a JSON object. Note how the `null` value was silently converted to a
5100 JSON object. Further note how no value is added if there was already one
5101 value stored with the same key.,emplace}
5102
5103 @since version 2.0.8
5104 */
5105 template<class... Args>
5106 std::pair<iterator, bool> emplace(Args&& ... args)
5107 {
5108 // emplace only works for null objects or arrays
5109 if (JSON_HEDLEY_UNLIKELY(not(is_null() or is_object())))
5110 {
5111 JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name())));
5112 }
5113
5114 // transform null object into an object
5115 if (is_null())
5116 {
5117 m_type = value_t::object;
5118 m_value = value_t::object;
5119 assert_invariant();
5120 }
5121
5122 // add element to array (perfect forwarding)
5123 auto res = m_value.object->emplace(std::forward<Args>(args)...);
5124 // create result iterator and set iterator to the result of emplace
5125 auto it = begin();
5126 it.m_it.object_iterator = res.first;
5127
5128 // return pair of iterator and boolean
5129 return {it, res.second};
5130 }
5131
5132 /// Helper for insertion of an iterator
5133 /// @note: This uses std::distance to support GCC 4.8,
5134 /// see https://github.com/nlohmann/json/pull/1257
5135 template<typename... Args>
5136 iterator insert_iterator(const_iterator pos, Args&& ... args)
5137 {
5138 iterator result(this);
5139 assert(m_value.array != nullptr);
5140
5141 auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator);
5142 m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...);
5143 result.m_it.array_iterator = m_value.array->begin() + insert_pos;
5144
5145 // This could have been written as:
5146 // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
5147 // but the return value of insert is missing in GCC 4.8, so it is written this way instead.
5148
5149 return result;
5150 }
5151
5152 /*!
5153 @brief inserts element
5154
5155 Inserts element @a val before iterator @a pos.
5156
5157 @param[in] pos iterator before which the content will be inserted; may be
5158 the end() iterator
5159 @param[in] val element to insert
5160 @return iterator pointing to the inserted @a val.
5161
5162 @throw type_error.309 if called on JSON values other than arrays;
5163 example: `"cannot use insert() with string"`
5164 @throw invalid_iterator.202 if @a pos is not an iterator of *this;
5165 example: `"iterator does not fit current value"`
5166
5167 @complexity Constant plus linear in the distance between @a pos and end of
5168 the container.
5169
5170 @liveexample{The example shows how `insert()` is used.,insert}
5171
5172 @since version 1.0.0
5173 */
5174 iterator insert(const_iterator pos, const basic_json& val)
5175 {
5176 // insert only works for arrays
5177 if (JSON_HEDLEY_LIKELY(is_array()))
5178 {
5179 // check if iterator pos fits to this JSON value
5180 if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
5181 {
5182 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
5183 }
5184
5185 // insert to array and return iterator
5186 return insert_iterator(pos, val);
5187 }
5188
5189 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
5190 }
5191
5192 /*!
5193 @brief inserts element
5194 @copydoc insert(const_iterator, const basic_json&)
5195 */
5196 iterator insert(const_iterator pos, basic_json&& val)
5197 {
5198 return insert(pos, val);
5199 }
5200
5201 /*!
5202 @brief inserts elements
5203
5204 Inserts @a cnt copies of @a val before iterator @a pos.
5205
5206 @param[in] pos iterator before which the content will be inserted; may be
5207 the end() iterator
5208 @param[in] cnt number of copies of @a val to insert
5209 @param[in] val element to insert
5210 @return iterator pointing to the first element inserted, or @a pos if
5211 `cnt==0`
5212
5213 @throw type_error.309 if called on JSON values other than arrays; example:
5214 `"cannot use insert() with string"`
5215 @throw invalid_iterator.202 if @a pos is not an iterator of *this;
5216 example: `"iterator does not fit current value"`
5217
5218 @complexity Linear in @a cnt plus linear in the distance between @a pos
5219 and end of the container.
5220
5221 @liveexample{The example shows how `insert()` is used.,insert__count}
5222
5223 @since version 1.0.0
5224 */
5225 iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
5226 {
5227 // insert only works for arrays
5228 if (JSON_HEDLEY_LIKELY(is_array()))
5229 {
5230 // check if iterator pos fits to this JSON value
5231 if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
5232 {
5233 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
5234 }
5235
5236 // insert to array and return iterator
5237 return insert_iterator(pos, cnt, val);
5238 }
5239
5240 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
5241 }
5242
5243 /*!
5244 @brief inserts elements
5245
5246 Inserts elements from range `[first, last)` before iterator @a pos.
5247
5248 @param[in] pos iterator before which the content will be inserted; may be
5249 the end() iterator
5250 @param[in] first begin of the range of elements to insert
5251 @param[in] last end of the range of elements to insert
5252
5253 @throw type_error.309 if called on JSON values other than arrays; example:
5254 `"cannot use insert() with string"`
5255 @throw invalid_iterator.202 if @a pos is not an iterator of *this;
5256 example: `"iterator does not fit current value"`
5257 @throw invalid_iterator.210 if @a first and @a last do not belong to the
5258 same JSON value; example: `"iterators do not fit"`
5259 @throw invalid_iterator.211 if @a first or @a last are iterators into
5260 container for which insert is called; example: `"passed iterators may not
5261 belong to container"`
5262
5263 @return iterator pointing to the first element inserted, or @a pos if
5264 `first==last`
5265
5266 @complexity Linear in `std::distance(first, last)` plus linear in the
5267 distance between @a pos and end of the container.
5268
5269 @liveexample{The example shows how `insert()` is used.,insert__range}
5270
5271 @since version 1.0.0
5272 */
5273 iterator insert(const_iterator pos, const_iterator first, const_iterator last)
5274 {
5275 // insert only works for arrays
5276 if (JSON_HEDLEY_UNLIKELY(not is_array()))
5277 {
5278 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
5279 }
5280
5281 // check if iterator pos fits to this JSON value
5282 if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
5283 {
5284 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
5285 }
5286
5287 // check if range iterators belong to the same JSON object
5288 if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
5289 {
5290 JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
5291 }
5292
5293 if (JSON_HEDLEY_UNLIKELY(first.m_object == this))
5294 {
5295 JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container"));
5296 }
5297
5298 // insert to array and return iterator
5299 return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator);
5300 }
5301
5302 /*!
5303 @brief inserts elements
5304
5305 Inserts elements from initializer list @a ilist before iterator @a pos.
5306
5307 @param[in] pos iterator before which the content will be inserted; may be
5308 the end() iterator
5309 @param[in] ilist initializer list to insert the values from
5310
5311 @throw type_error.309 if called on JSON values other than arrays; example:
5312 `"cannot use insert() with string"`
5313 @throw invalid_iterator.202 if @a pos is not an iterator of *this;
5314 example: `"iterator does not fit current value"`
5315
5316 @return iterator pointing to the first element inserted, or @a pos if
5317 `ilist` is empty
5318
5319 @complexity Linear in `ilist.size()` plus linear in the distance between
5320 @a pos and end of the container.
5321
5322 @liveexample{The example shows how `insert()` is used.,insert__ilist}
5323
5324 @since version 1.0.0
5325 */
5326 iterator insert(const_iterator pos, initializer_list_t ilist)
5327 {
5328 // insert only works for arrays
5329 if (JSON_HEDLEY_UNLIKELY(not is_array()))
5330 {
5331 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
5332 }
5333
5334 // check if iterator pos fits to this JSON value
5335 if (JSON_HEDLEY_UNLIKELY(pos.m_object != this))
5336 {
5337 JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value"));
5338 }
5339
5340 // insert to array and return iterator
5341 return insert_iterator(pos, ilist.begin(), ilist.end());
5342 }
5343
5344 /*!
5345 @brief inserts elements
5346
5347 Inserts elements from range `[first, last)`.
5348
5349 @param[in] first begin of the range of elements to insert
5350 @param[in] last end of the range of elements to insert
5351
5352 @throw type_error.309 if called on JSON values other than objects; example:
5353 `"cannot use insert() with string"`
5354 @throw invalid_iterator.202 if iterator @a first or @a last does does not
5355 point to an object; example: `"iterators first and last must point to
5356 objects"`
5357 @throw invalid_iterator.210 if @a first and @a last do not belong to the
5358 same JSON value; example: `"iterators do not fit"`
5359
5360 @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number
5361 of elements to insert.
5362
5363 @liveexample{The example shows how `insert()` is used.,insert__range_object}
5364
5365 @since version 3.0.0
5366 */
5367 void insert(const_iterator first, const_iterator last)
5368 {
5369 // insert only works for objects
5370 if (JSON_HEDLEY_UNLIKELY(not is_object()))
5371 {
5372 JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name())));
5373 }
5374
5375 // check if range iterators belong to the same JSON object
5376 if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
5377 {
5378 JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
5379 }
5380
5381 // passed iterators must belong to objects
5382 if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()))
5383 {
5384 JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
5385 }
5386
5387 m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator);
5388 }
5389
5390 /*!
5391 @brief updates a JSON object from another object, overwriting existing keys
5392
5393 Inserts all values from JSON object @a j and overwrites existing keys.
5394
5395 @param[in] j JSON object to read values from
5396
5397 @throw type_error.312 if called on JSON values other than objects; example:
5398 `"cannot use update() with string"`
5399
5400 @complexity O(N*log(size() + N)), where N is the number of elements to
5401 insert.
5402
5403 @liveexample{The example shows how `update()` is used.,update}
5404
5405 @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
5406
5407 @since version 3.0.0
5408 */
5409 void update(const_reference j)
5410 {
5411 // implicitly convert null value to an empty object
5412 if (is_null())
5413 {
5414 m_type = value_t::object;
5415 m_value.object = create<object_t>();
5416 assert_invariant();
5417 }
5418
5419 if (JSON_HEDLEY_UNLIKELY(not is_object()))
5420 {
5421 JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
5422 }
5423 if (JSON_HEDLEY_UNLIKELY(not j.is_object()))
5424 {
5425 JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name())));
5426 }
5427
5428 for (auto it = j.cbegin(); it != j.cend(); ++it)
5429 {
5430 m_value.object->operator[](it.key()) = it.value();
5431 }
5432 }
5433
5434 /*!
5435 @brief updates a JSON object from another object, overwriting existing keys
5436
5437 Inserts all values from from range `[first, last)` and overwrites existing
5438 keys.
5439
5440 @param[in] first begin of the range of elements to insert
5441 @param[in] last end of the range of elements to insert
5442
5443 @throw type_error.312 if called on JSON values other than objects; example:
5444 `"cannot use update() with string"`
5445 @throw invalid_iterator.202 if iterator @a first or @a last does does not
5446 point to an object; example: `"iterators first and last must point to
5447 objects"`
5448 @throw invalid_iterator.210 if @a first and @a last do not belong to the
5449 same JSON value; example: `"iterators do not fit"`
5450
5451 @complexity O(N*log(size() + N)), where N is the number of elements to
5452 insert.
5453
5454 @liveexample{The example shows how `update()` is used__range.,update}
5455
5456 @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update
5457
5458 @since version 3.0.0
5459 */
5460 void update(const_iterator first, const_iterator last)
5461 {
5462 // implicitly convert null value to an empty object
5463 if (is_null())
5464 {
5465 m_type = value_t::object;
5466 m_value.object = create<object_t>();
5467 assert_invariant();
5468 }
5469
5470 if (JSON_HEDLEY_UNLIKELY(not is_object()))
5471 {
5472 JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name())));
5473 }
5474
5475 // check if range iterators belong to the same JSON object
5476 if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object))
5477 {
5478 JSON_THROW(invalid_iterator::create(210, "iterators do not fit"));
5479 }
5480
5481 // passed iterators must belong to objects
5482 if (JSON_HEDLEY_UNLIKELY(not first.m_object->is_object()
5483 or not last.m_object->is_object()))
5484 {
5485 JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects"));
5486 }
5487
5488 for (auto it = first; it != last; ++it)
5489 {
5490 m_value.object->operator[](it.key()) = it.value();
5491 }
5492 }
5493
5494 /*!
5495 @brief exchanges the values
5496
5497 Exchanges the contents of the JSON value with those of @a other. Does not
5498 invoke any move, copy, or swap operations on individual elements. All
5499 iterators and references remain valid. The past-the-end iterator is
5500 invalidated.
5501
5502 @param[in,out] other JSON value to exchange the contents with
5503
5504 @complexity Constant.
5505
5506 @liveexample{The example below shows how JSON values can be swapped with
5507 `swap()`.,swap__reference}
5508
5509 @since version 1.0.0
5510 */
5511 void swap(reference other) noexcept (
5512 std::is_nothrow_move_constructible<value_t>::value and
5513 std::is_nothrow_move_assignable<value_t>::value and
5514 std::is_nothrow_move_constructible<json_value>::value and
5515 std::is_nothrow_move_assignable<json_value>::value
5516 )
5517 {
5518 std::swap(m_type, other.m_type);
5519 std::swap(m_value, other.m_value);
5520 assert_invariant();
5521 }
5522
5523 /*!
5524 @brief exchanges the values
5525
5526 Exchanges the contents of a JSON array with those of @a other. Does not
5527 invoke any move, copy, or swap operations on individual elements. All
5528 iterators and references remain valid. The past-the-end iterator is
5529 invalidated.
5530
5531 @param[in,out] other array to exchange the contents with
5532
5533 @throw type_error.310 when JSON value is not an array; example: `"cannot
5534 use swap() with string"`
5535
5536 @complexity Constant.
5537
5538 @liveexample{The example below shows how arrays can be swapped with
5539 `swap()`.,swap__array_t}
5540
5541 @since version 1.0.0
5542 */
5543 void swap(array_t& other)
5544 {
5545 // swap only works for arrays
5546 if (JSON_HEDLEY_LIKELY(is_array()))
5547 {
5548 std::swap(*(m_value.array), other);
5549 }
5550 else
5551 {
5552 JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
5553 }
5554 }
5555
5556 /*!
5557 @brief exchanges the values
5558
5559 Exchanges the contents of a JSON object with those of @a other. Does not
5560 invoke any move, copy, or swap operations on individual elements. All
5561 iterators and references remain valid. The past-the-end iterator is
5562 invalidated.
5563
5564 @param[in,out] other object to exchange the contents with
5565
5566 @throw type_error.310 when JSON value is not an object; example:
5567 `"cannot use swap() with string"`
5568
5569 @complexity Constant.
5570
5571 @liveexample{The example below shows how objects can be swapped with
5572 `swap()`.,swap__object_t}
5573
5574 @since version 1.0.0
5575 */
5576 void swap(object_t& other)
5577 {
5578 // swap only works for objects
5579 if (JSON_HEDLEY_LIKELY(is_object()))
5580 {
5581 std::swap(*(m_value.object), other);
5582 }
5583 else
5584 {
5585 JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
5586 }
5587 }
5588
5589 /*!
5590 @brief exchanges the values
5591
5592 Exchanges the contents of a JSON string with those of @a other. Does not
5593 invoke any move, copy, or swap operations on individual elements. All
5594 iterators and references remain valid. The past-the-end iterator is
5595 invalidated.
5596
5597 @param[in,out] other string to exchange the contents with
5598
5599 @throw type_error.310 when JSON value is not a string; example: `"cannot
5600 use swap() with boolean"`
5601
5602 @complexity Constant.
5603
5604 @liveexample{The example below shows how strings can be swapped with
5605 `swap()`.,swap__string_t}
5606
5607 @since version 1.0.0
5608 */
5609 void swap(string_t& other)
5610 {
5611 // swap only works for strings
5612 if (JSON_HEDLEY_LIKELY(is_string()))
5613 {
5614 std::swap(*(m_value.string), other);
5615 }
5616 else
5617 {
5618 JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name())));
5619 }
5620 }
5621
5622 /// @}
5623
5624 public:
5625 //////////////////////////////////////////
5626 // lexicographical comparison operators //
5627 //////////////////////////////////////////
5628
5629 /// @name lexicographical comparison operators
5630 /// @{
5631
5632 /*!
5633 @brief comparison: equal
5634
5635 Compares two JSON values for equality according to the following rules:
5636 - Two JSON values are equal if (1) they are from the same type and (2)
5637 their stored values are the same according to their respective
5638 `operator==`.
5639 - Integer and floating-point numbers are automatically converted before
5640 comparison. Note than two NaN values are always treated as unequal.
5641 - Two JSON null values are equal.
5642
5643 @note Floating-point inside JSON values numbers are compared with
5644 `json::number_float_t::operator==` which is `double::operator==` by
5645 default. To compare floating-point while respecting an epsilon, an alternative
5646 [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39)
5647 could be used, for instance
5648 @code {.cpp}
5649 template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type>
5650 inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept
5651 {
5652 return std::abs(a - b) <= epsilon;
5653 }
5654 @endcode
5655
5656 @note NaN values never compare equal to themselves or to other NaN values.
5657
5658 @param[in] lhs first JSON value to consider
5659 @param[in] rhs second JSON value to consider
5660 @return whether the values @a lhs and @a rhs are equal
5661
5662 @exceptionsafety No-throw guarantee: this function never throws exceptions.
5663
5664 @complexity Linear.
5665
5666 @liveexample{The example demonstrates comparing several JSON
5667 types.,operator__equal}
5668
5669 @since version 1.0.0
5670 */
5671 friend bool operator==(const_reference lhs, const_reference rhs) noexcept
5672 {
5673 const auto lhs_type = lhs.type();
5674 const auto rhs_type = rhs.type();
5675
5676 if (lhs_type == rhs_type)
5677 {
5678 switch (lhs_type)
5679 {
5680 case value_t::array:
5681 return *lhs.m_value.array == *rhs.m_value.array;
5682
5683 case value_t::object:
5684 return *lhs.m_value.object == *rhs.m_value.object;
5685
5686 case value_t::null:
5687 return true;
5688
5689 case value_t::string:
5690 return *lhs.m_value.string == *rhs.m_value.string;
5691
5692 case value_t::boolean:
5693 return lhs.m_value.boolean == rhs.m_value.boolean;
5694
5695 case value_t::number_integer:
5696 return lhs.m_value.number_integer == rhs.m_value.number_integer;
5697
5698 case value_t::number_unsigned:
5699 return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned;
5700
5701 case value_t::number_float:
5702 return lhs.m_value.number_float == rhs.m_value.number_float;
5703
5704 default:
5705 return false;
5706 }
5707 }
5708 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
5709 {
5710 return static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float;
5711 }
5712 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
5713 {
5714 return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer);
5715 }
5716 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
5717 {
5718 return static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float;
5719 }
5720 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
5721 {
5722 return lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned);
5723 }
5724 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
5725 {
5726 return static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer;
5727 }
5728 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
5729 {
5730 return lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned);
5731 }
5732
5733 return false;
5734 }
5735
5736 /*!
5737 @brief comparison: equal
5738 @copydoc operator==(const_reference, const_reference)
5739 */
5740 template<typename ScalarType, typename std::enable_if<
5741 std::is_scalar<ScalarType>::value, int>::type = 0>
5742 friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept
5743 {
5744 return lhs == basic_json(rhs);
5745 }
5746
5747 /*!
5748 @brief comparison: equal
5749 @copydoc operator==(const_reference, const_reference)
5750 */
5751 template<typename ScalarType, typename std::enable_if<
5752 std::is_scalar<ScalarType>::value, int>::type = 0>
5753 friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept
5754 {
5755 return basic_json(lhs) == rhs;
5756 }
5757
5758 /*!
5759 @brief comparison: not equal
5760
5761 Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
5762
5763 @param[in] lhs first JSON value to consider
5764 @param[in] rhs second JSON value to consider
5765 @return whether the values @a lhs and @a rhs are not equal
5766
5767 @complexity Linear.
5768
5769 @exceptionsafety No-throw guarantee: this function never throws exceptions.
5770
5771 @liveexample{The example demonstrates comparing several JSON
5772 types.,operator__notequal}
5773
5774 @since version 1.0.0
5775 */
5776 friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
5777 {
5778 return not (lhs == rhs);
5779 }
5780
5781 /*!
5782 @brief comparison: not equal
5783 @copydoc operator!=(const_reference, const_reference)
5784 */
5785 template<typename ScalarType, typename std::enable_if<
5786 std::is_scalar<ScalarType>::value, int>::type = 0>
5787 friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept
5788 {
5789 return lhs != basic_json(rhs);
5790 }
5791
5792 /*!
5793 @brief comparison: not equal
5794 @copydoc operator!=(const_reference, const_reference)
5795 */
5796 template<typename ScalarType, typename std::enable_if<
5797 std::is_scalar<ScalarType>::value, int>::type = 0>
5798 friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept
5799 {
5800 return basic_json(lhs) != rhs;
5801 }
5802
5803 /*!
5804 @brief comparison: less than
5805
5806 Compares whether one JSON value @a lhs is less than another JSON value @a
5807 rhs according to the following rules:
5808 - If @a lhs and @a rhs have the same type, the values are compared using
5809 the default `<` operator.
5810 - Integer and floating-point numbers are automatically converted before
5811 comparison
5812 - In case @a lhs and @a rhs have different types, the values are ignored
5813 and the order of the types is considered, see
5814 @ref operator<(const value_t, const value_t).
5815
5816 @param[in] lhs first JSON value to consider
5817 @param[in] rhs second JSON value to consider
5818 @return whether @a lhs is less than @a rhs
5819
5820 @complexity Linear.
5821
5822 @exceptionsafety No-throw guarantee: this function never throws exceptions.
5823
5824 @liveexample{The example demonstrates comparing several JSON
5825 types.,operator__less}
5826
5827 @since version 1.0.0
5828 */
5829 friend bool operator<(const_reference lhs, const_reference rhs) noexcept
5830 {
5831 const auto lhs_type = lhs.type();
5832 const auto rhs_type = rhs.type();
5833
5834 if (lhs_type == rhs_type)
5835 {
5836 switch (lhs_type)
5837 {
5838 case value_t::array:
5839 // note parentheses are necessary, see
5840 // https://github.com/nlohmann/json/issues/1530
5841 return (*lhs.m_value.array) < (*rhs.m_value.array);
5842
5843 case value_t::object:
5844 return (*lhs.m_value.object) < (*rhs.m_value.object);
5845
5846 case value_t::null:
5847 return false;
5848
5849 case value_t::string:
5850 return (*lhs.m_value.string) < (*rhs.m_value.string);
5851
5852 case value_t::boolean:
5853 return (lhs.m_value.boolean) < (rhs.m_value.boolean);
5854
5855 case value_t::number_integer:
5856 return (lhs.m_value.number_integer) < (rhs.m_value.number_integer);
5857
5858 case value_t::number_unsigned:
5859 return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned);
5860
5861 case value_t::number_float:
5862 return (lhs.m_value.number_float) < (rhs.m_value.number_float);
5863
5864 default:
5865 return false;
5866 }
5867 }
5868 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
5869 {
5870 return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float;
5871 }
5872 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
5873 {
5874 return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer);
5875 }
5876 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float)
5877 {
5878 return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float;
5879 }
5880 else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned)
5881 {
5882 return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned);
5883 }
5884 else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned)
5885 {
5886 return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned);
5887 }
5888 else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer)
5889 {
5890 return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer;
5891 }
5892
5893 // We only reach this line if we cannot compare values. In that case,
5894 // we compare types. Note we have to call the operator explicitly,
5895 // because MSVC has problems otherwise.
5896 return operator<(lhs_type, rhs_type);
5897 }
5898
5899 /*!
5900 @brief comparison: less than
5901 @copydoc operator<(const_reference, const_reference)
5902 */
5903 template<typename ScalarType, typename std::enable_if<
5904 std::is_scalar<ScalarType>::value, int>::type = 0>
5905 friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept
5906 {
5907 return lhs < basic_json(rhs);
5908 }
5909
5910 /*!
5911 @brief comparison: less than
5912 @copydoc operator<(const_reference, const_reference)
5913 */
5914 template<typename ScalarType, typename std::enable_if<
5915 std::is_scalar<ScalarType>::value, int>::type = 0>
5916 friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept
5917 {
5918 return basic_json(lhs) < rhs;
5919 }
5920
5921 /*!
5922 @brief comparison: less than or equal
5923
5924 Compares whether one JSON value @a lhs is less than or equal to another
5925 JSON value by calculating `not (rhs < lhs)`.
5926
5927 @param[in] lhs first JSON value to consider
5928 @param[in] rhs second JSON value to consider
5929 @return whether @a lhs is less than or equal to @a rhs
5930
5931 @complexity Linear.
5932
5933 @exceptionsafety No-throw guarantee: this function never throws exceptions.
5934
5935 @liveexample{The example demonstrates comparing several JSON
5936 types.,operator__greater}
5937
5938 @since version 1.0.0
5939 */
5940 friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
5941 {
5942 return not (rhs < lhs);
5943 }
5944
5945 /*!
5946 @brief comparison: less than or equal
5947 @copydoc operator<=(const_reference, const_reference)
5948 */
5949 template<typename ScalarType, typename std::enable_if<
5950 std::is_scalar<ScalarType>::value, int>::type = 0>
5951 friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept
5952 {
5953 return lhs <= basic_json(rhs);
5954 }
5955
5956 /*!
5957 @brief comparison: less than or equal
5958 @copydoc operator<=(const_reference, const_reference)
5959 */
5960 template<typename ScalarType, typename std::enable_if<
5961 std::is_scalar<ScalarType>::value, int>::type = 0>
5962 friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept
5963 {
5964 return basic_json(lhs) <= rhs;
5965 }
5966
5967 /*!
5968 @brief comparison: greater than
5969
5970 Compares whether one JSON value @a lhs is greater than another
5971 JSON value by calculating `not (lhs <= rhs)`.
5972
5973 @param[in] lhs first JSON value to consider
5974 @param[in] rhs second JSON value to consider
5975 @return whether @a lhs is greater than to @a rhs
5976
5977 @complexity Linear.
5978
5979 @exceptionsafety No-throw guarantee: this function never throws exceptions.
5980
5981 @liveexample{The example demonstrates comparing several JSON
5982 types.,operator__lessequal}
5983
5984 @since version 1.0.0
5985 */
5986 friend bool operator>(const_reference lhs, const_reference rhs) noexcept
5987 {
5988 return not (lhs <= rhs);
5989 }
5990
5991 /*!
5992 @brief comparison: greater than
5993 @copydoc operator>(const_reference, const_reference)
5994 */
5995 template<typename ScalarType, typename std::enable_if<
5996 std::is_scalar<ScalarType>::value, int>::type = 0>
5997 friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept
5998 {
5999 return lhs > basic_json(rhs);
6000 }
6001
6002 /*!
6003 @brief comparison: greater than
6004 @copydoc operator>(const_reference, const_reference)
6005 */
6006 template<typename ScalarType, typename std::enable_if<
6007 std::is_scalar<ScalarType>::value, int>::type = 0>
6008 friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept
6009 {
6010 return basic_json(lhs) > rhs;
6011 }
6012
6013 /*!
6014 @brief comparison: greater than or equal
6015
6016 Compares whether one JSON value @a lhs is greater than or equal to another
6017 JSON value by calculating `not (lhs < rhs)`.
6018
6019 @param[in] lhs first JSON value to consider
6020 @param[in] rhs second JSON value to consider
6021 @return whether @a lhs is greater than or equal to @a rhs
6022
6023 @complexity Linear.
6024
6025 @exceptionsafety No-throw guarantee: this function never throws exceptions.
6026
6027 @liveexample{The example demonstrates comparing several JSON
6028 types.,operator__greaterequal}
6029
6030 @since version 1.0.0
6031 */
6032 friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
6033 {
6034 return not (lhs < rhs);
6035 }
6036
6037 /*!
6038 @brief comparison: greater than or equal
6039 @copydoc operator>=(const_reference, const_reference)
6040 */
6041 template<typename ScalarType, typename std::enable_if<
6042 std::is_scalar<ScalarType>::value, int>::type = 0>
6043 friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept
6044 {
6045 return lhs >= basic_json(rhs);
6046 }
6047
6048 /*!
6049 @brief comparison: greater than or equal
6050 @copydoc operator>=(const_reference, const_reference)
6051 */
6052 template<typename ScalarType, typename std::enable_if<
6053 std::is_scalar<ScalarType>::value, int>::type = 0>
6054 friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept
6055 {
6056 return basic_json(lhs) >= rhs;
6057 }
6058
6059 /// @}
6060
6061 ///////////////////
6062 // serialization //
6063 ///////////////////
6064
6065 /// @name serialization
6066 /// @{
6067
6068 /*!
6069 @brief serialize to stream
6070
6071 Serialize the given JSON value @a j to the output stream @a o. The JSON
6072 value will be serialized using the @ref dump member function.
6073
6074 - The indentation of the output can be controlled with the member variable
6075 `width` of the output stream @a o. For instance, using the manipulator
6076 `std::setw(4)` on @a o sets the indentation level to `4` and the
6077 serialization result is the same as calling `dump(4)`.
6078
6079 - The indentation character can be controlled with the member variable
6080 `fill` of the output stream @a o. For instance, the manipulator
6081 `std::setfill('\\t')` sets indentation to use a tab character rather than
6082 the default space character.
6083
6084 @param[in,out] o stream to serialize to
6085 @param[in] j JSON value to serialize
6086
6087 @return the stream @a o
6088
6089 @throw type_error.316 if a string stored inside the JSON value is not
6090 UTF-8 encoded
6091
6092 @complexity Linear.
6093
6094 @liveexample{The example below shows the serialization with different
6095 parameters to `width` to adjust the indentation level.,operator_serialize}
6096
6097 @since version 1.0.0; indentation character added in version 3.0.0
6098 */
6099 friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
6100 {
6101 // read width member and use it as indentation parameter if nonzero
6102 const bool pretty_print = o.width() > 0;
6103 const auto indentation = pretty_print ? o.width() : 0;
6104
6105 // reset width to 0 for subsequent calls to this stream
6106 o.width(0);
6107
6108 // do the actual serialization
6109 serializer s(detail::output_adapter<char>(o), o.fill());
6110 s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation));
6111 return o;
6112 }
6113
6114 /*!
6115 @brief serialize to stream
6116 @deprecated This stream operator is deprecated and will be removed in
6117 future 4.0.0 of the library. Please use
6118 @ref operator<<(std::ostream&, const basic_json&)
6119 instead; that is, replace calls like `j >> o;` with `o << j;`.
6120 @since version 1.0.0; deprecated since version 3.0.0
6121 */
6122 JSON_HEDLEY_DEPRECATED(3.0.0)
6123 friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
6124 {
6125 return o << j;
6126 }
6127
6128 /// @}
6129
6130
6131 /////////////////////
6132 // deserialization //
6133 /////////////////////
6134
6135 /// @name deserialization
6136 /// @{
6137
6138 /*!
6139 @brief deserialize from a compatible input
6140
6141 This function reads from a compatible input. Examples are:
6142 - an array of 1-byte values
6143 - strings with character/literal type with size of 1 byte
6144 - input streams
6145 - container with contiguous storage of 1-byte values. Compatible container
6146 types include `std::vector`, `std::string`, `std::array`,
6147 `std::valarray`, and `std::initializer_list`. Furthermore, C-style
6148 arrays can be used with `std::begin()`/`std::end()`. User-defined
6149 containers can be used as long as they implement random-access iterators
6150 and a contiguous storage.
6151
6152 @pre Each element of the container has a size of 1 byte. Violating this
6153 precondition yields undefined behavior. **This precondition is enforced
6154 with a static assertion.**
6155
6156 @pre The container storage is contiguous. Violating this precondition
6157 yields undefined behavior. **This precondition is enforced with an
6158 assertion.**
6159
6160 @warning There is no way to enforce all preconditions at compile-time. If
6161 the function is called with a noncompliant container and with
6162 assertions switched off, the behavior is undefined and will most
6163 likely yield segmentation violation.
6164
6165 @param[in] i input to read from
6166 @param[in] cb a parser callback function of type @ref parser_callback_t
6167 which is used to control the deserialization by filtering unwanted values
6168 (optional)
6169 @param[in] allow_exceptions whether to throw exceptions in case of a
6170 parse error (optional, true by default)
6171
6172 @return deserialized JSON value; in case of a parse error and
6173 @a allow_exceptions set to `false`, the return value will be
6174 value_t::discarded.
6175
6176 @throw parse_error.101 if a parse error occurs; example: `""unexpected end
6177 of input; expected string literal""`
6178 @throw parse_error.102 if to_unicode fails or surrogate error
6179 @throw parse_error.103 if to_unicode fails
6180
6181 @complexity Linear in the length of the input. The parser is a predictive
6182 LL(1) parser. The complexity can be higher if the parser callback function
6183 @a cb has a super-linear complexity.
6184
6185 @note A UTF-8 byte order mark is silently ignored.
6186
6187 @liveexample{The example below demonstrates the `parse()` function reading
6188 from an array.,parse__array__parser_callback_t}
6189
6190 @liveexample{The example below demonstrates the `parse()` function with
6191 and without callback function.,parse__string__parser_callback_t}
6192
6193 @liveexample{The example below demonstrates the `parse()` function with
6194 and without callback function.,parse__istream__parser_callback_t}
6195
6196 @liveexample{The example below demonstrates the `parse()` function reading
6197 from a contiguous container.,parse__contiguouscontainer__parser_callback_t}
6198
6199 @since version 2.0.3 (contiguous containers)
6200 */
6201 JSON_HEDLEY_WARN_UNUSED_RESULT
6202 static basic_json parse(detail::input_adapter&& i,
6203 const parser_callback_t cb = nullptr,
6204 const bool allow_exceptions = true)
6205 {
6206 basic_json result;
6207 parser(i, cb, allow_exceptions).parse(true, result);
6208 return result;
6209 }
6210
6211 static bool accept(detail::input_adapter&& i)
6212 {
6213 return parser(i).accept(true);
6214 }
6215
6216 /*!
6217 @brief generate SAX events
6218
6219 The SAX event lister must follow the interface of @ref json_sax.
6220
6221 This function reads from a compatible input. Examples are:
6222 - an array of 1-byte values
6223 - strings with character/literal type with size of 1 byte
6224 - input streams
6225 - container with contiguous storage of 1-byte values. Compatible container
6226 types include `std::vector`, `std::string`, `std::array`,
6227 `std::valarray`, and `std::initializer_list`. Furthermore, C-style
6228 arrays can be used with `std::begin()`/`std::end()`. User-defined
6229 containers can be used as long as they implement random-access iterators
6230 and a contiguous storage.
6231
6232 @pre Each element of the container has a size of 1 byte. Violating this
6233 precondition yields undefined behavior. **This precondition is enforced
6234 with a static assertion.**
6235
6236 @pre The container storage is contiguous. Violating this precondition
6237 yields undefined behavior. **This precondition is enforced with an
6238 assertion.**
6239
6240 @warning There is no way to enforce all preconditions at compile-time. If
6241 the function is called with a noncompliant container and with
6242 assertions switched off, the behavior is undefined and will most
6243 likely yield segmentation violation.
6244
6245 @param[in] i input to read from
6246 @param[in,out] sax SAX event listener
6247 @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON)
6248 @param[in] strict whether the input has to be consumed completely
6249
6250 @return return value of the last processed SAX event
6251
6252 @throw parse_error.101 if a parse error occurs; example: `""unexpected end
6253 of input; expected string literal""`
6254 @throw parse_error.102 if to_unicode fails or surrogate error
6255 @throw parse_error.103 if to_unicode fails
6256
6257 @complexity Linear in the length of the input. The parser is a predictive
6258 LL(1) parser. The complexity can be higher if the SAX consumer @a sax has
6259 a super-linear complexity.
6260
6261 @note A UTF-8 byte order mark is silently ignored.
6262
6263 @liveexample{The example below demonstrates the `sax_parse()` function
6264 reading from string and processing the events with a user-defined SAX
6265 event consumer.,sax_parse}
6266
6267 @since version 3.2.0
6268 */
6269 template <typename SAX>
6270 JSON_HEDLEY_NON_NULL(2)
6271 static bool sax_parse(detail::input_adapter&& i, SAX* sax,
6272 input_format_t format = input_format_t::json,
6273 const bool strict = true)
6274 {
6275 assert(sax);
6276 return format == input_format_t::json
6277 ? parser(std::move(i)).sax_parse(sax, strict)
6278 : detail::binary_reader<basic_json, SAX>(std::move(i)).sax_parse(format, sax, strict);
6279 }
6280
6281 /*!
6282 @brief deserialize from an iterator range with contiguous storage
6283
6284 This function reads from an iterator range of a container with contiguous
6285 storage of 1-byte values. Compatible container types include
6286 `std::vector`, `std::string`, `std::array`, `std::valarray`, and
6287 `std::initializer_list`. Furthermore, C-style arrays can be used with
6288 `std::begin()`/`std::end()`. User-defined containers can be used as long
6289 as they implement random-access iterators and a contiguous storage.
6290
6291 @pre The iterator range is contiguous. Violating this precondition yields
6292 undefined behavior. **This precondition is enforced with an assertion.**
6293 @pre Each element in the range has a size of 1 byte. Violating this
6294 precondition yields undefined behavior. **This precondition is enforced
6295 with a static assertion.**
6296
6297 @warning There is no way to enforce all preconditions at compile-time. If
6298 the function is called with noncompliant iterators and with
6299 assertions switched off, the behavior is undefined and will most
6300 likely yield segmentation violation.
6301
6302 @tparam IteratorType iterator of container with contiguous storage
6303 @param[in] first begin of the range to parse (included)
6304 @param[in] last end of the range to parse (excluded)
6305 @param[in] cb a parser callback function of type @ref parser_callback_t
6306 which is used to control the deserialization by filtering unwanted values
6307 (optional)
6308 @param[in] allow_exceptions whether to throw exceptions in case of a
6309 parse error (optional, true by default)
6310
6311 @return deserialized JSON value; in case of a parse error and
6312 @a allow_exceptions set to `false`, the return value will be
6313 value_t::discarded.
6314
6315 @throw parse_error.101 in case of an unexpected token
6316 @throw parse_error.102 if to_unicode fails or surrogate error
6317 @throw parse_error.103 if to_unicode fails
6318
6319 @complexity Linear in the length of the input. The parser is a predictive
6320 LL(1) parser. The complexity can be higher if the parser callback function
6321 @a cb has a super-linear complexity.
6322
6323 @note A UTF-8 byte order mark is silently ignored.
6324
6325 @liveexample{The example below demonstrates the `parse()` function reading
6326 from an iterator range.,parse__iteratortype__parser_callback_t}
6327
6328 @since version 2.0.3
6329 */
6330 template<class IteratorType, typename std::enable_if<
6331 std::is_base_of<
6332 std::random_access_iterator_tag,
6333 typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
6334 static basic_json parse(IteratorType first, IteratorType last,
6335 const parser_callback_t cb = nullptr,
6336 const bool allow_exceptions = true)
6337 {
6338 basic_json result;
6339 parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result);
6340 return result;
6341 }
6342
6343 template<class IteratorType, typename std::enable_if<
6344 std::is_base_of<
6345 std::random_access_iterator_tag,
6346 typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
6347 static bool accept(IteratorType first, IteratorType last)
6348 {
6349 return parser(detail::input_adapter(first, last)).accept(true);
6350 }
6351
6352 template<class IteratorType, class SAX, typename std::enable_if<
6353 std::is_base_of<
6354 std::random_access_iterator_tag,
6355 typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0>
6356 JSON_HEDLEY_NON_NULL(3)
6357 static bool sax_parse(IteratorType first, IteratorType last, SAX* sax)
6358 {
6359 return parser(detail::input_adapter(first, last)).sax_parse(sax);
6360 }
6361
6362 /*!
6363 @brief deserialize from stream
6364 @deprecated This stream operator is deprecated and will be removed in
6365 version 4.0.0 of the library. Please use
6366 @ref operator>>(std::istream&, basic_json&)
6367 instead; that is, replace calls like `j << i;` with `i >> j;`.
6368 @since version 1.0.0; deprecated since version 3.0.0
6369 */
6370 JSON_HEDLEY_DEPRECATED(3.0.0)
6371 friend std::istream& operator<<(basic_json& j, std::istream& i)
6372 {
6373 return operator>>(i, j);
6374 }
6375
6376 /*!
6377 @brief deserialize from stream
6378
6379 Deserializes an input stream to a JSON value.
6380
6381 @param[in,out] i input stream to read a serialized JSON value from
6382 @param[in,out] j JSON value to write the deserialized input to
6383
6384 @throw parse_error.101 in case of an unexpected token
6385 @throw parse_error.102 if to_unicode fails or surrogate error
6386 @throw parse_error.103 if to_unicode fails
6387
6388 @complexity Linear in the length of the input. The parser is a predictive
6389 LL(1) parser.
6390
6391 @note A UTF-8 byte order mark is silently ignored.
6392
6393 @liveexample{The example below shows how a JSON value is constructed by
6394 reading a serialization from a stream.,operator_deserialize}
6395
6396 @sa parse(std::istream&, const parser_callback_t) for a variant with a
6397 parser callback function to filter values while parsing
6398
6399 @since version 1.0.0
6400 */
6401 friend std::istream& operator>>(std::istream& i, basic_json& j)
6402 {
6403 parser(detail::input_adapter(i)).parse(false, j);
6404 return i;
6405 }
6406
6407 /// @}
6408
6409 ///////////////////////////
6410 // convenience functions //
6411 ///////////////////////////
6412
6413 /*!
6414 @brief return the type as string
6415
6416 Returns the type name as string to be used in error messages - usually to
6417 indicate that a function was called on a wrong JSON type.
6418
6419 @return a string representation of a the @a m_type member:
6420 Value type | return value
6421 ----------- | -------------
6422 null | `"null"`
6423 boolean | `"boolean"`
6424 string | `"string"`
6425 number | `"number"` (for all number types)
6426 object | `"object"`
6427 array | `"array"`
6428 discarded | `"discarded"`
6429
6430 @exceptionsafety No-throw guarantee: this function never throws exceptions.
6431
6432 @complexity Constant.
6433
6434 @liveexample{The following code exemplifies `type_name()` for all JSON
6435 types.,type_name}
6436
6437 @sa @ref type() -- return the type of the JSON value
6438 @sa @ref operator value_t() -- return the type of the JSON value (implicit)
6439
6440 @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept`
6441 since 3.0.0
6442 */
6443 JSON_HEDLEY_RETURNS_NON_NULL
6444 const char* type_name() const noexcept
6445 {
6446 {
6447 switch (m_type)
6448 {
6449 case value_t::null:
6450 return "null";
6451 case value_t::object:
6452 return "object";
6453 case value_t::array:
6454 return "array";
6455 case value_t::string:
6456 return "string";
6457 case value_t::boolean:
6458 return "boolean";
6459 case value_t::discarded:
6460 return "discarded";
6461 default:
6462 return "number";
6463 }
6464 }
6465 }
6466
6467
6468 private:
6469 //////////////////////
6470 // member variables //
6471 //////////////////////
6472
6473 /// the type of the current element
6474 value_t m_type = value_t::null;
6475
6476 /// the value of the current element
6477 json_value m_value = {};
6478
6479 //////////////////////////////////////////
6480 // binary serialization/deserialization //
6481 //////////////////////////////////////////
6482
6483 /// @name binary serialization/deserialization support
6484 /// @{
6485
6486 public:
6487 /*!
6488 @brief create a CBOR serialization of a given JSON value
6489
6490 Serializes a given JSON value @a j to a byte vector using the CBOR (Concise
6491 Binary Object Representation) serialization format. CBOR is a binary
6492 serialization format which aims to be more compact than JSON itself, yet
6493 more efficient to parse.
6494
6495 The library uses the following mapping from JSON values types to
6496 CBOR types according to the CBOR specification (RFC 7049):
6497
6498 JSON value type | value/range | CBOR type | first byte
6499 --------------- | ------------------------------------------ | ---------------------------------- | ---------------
6500 null | `null` | Null | 0xF6
6501 boolean | `true` | True | 0xF5
6502 boolean | `false` | False | 0xF4
6503 number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B
6504 number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A
6505 number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39
6506 number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38
6507 number_integer | -24..-1 | Negative integer | 0x20..0x37
6508 number_integer | 0..23 | Integer | 0x00..0x17
6509 number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18
6510 number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
6511 number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
6512 number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
6513 number_unsigned | 0..23 | Integer | 0x00..0x17
6514 number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18
6515 number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19
6516 number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A
6517 number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B
6518 number_float | *any value* | Double-Precision Float | 0xFB
6519 string | *length*: 0..23 | UTF-8 string | 0x60..0x77
6520 string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78
6521 string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79
6522 string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A
6523 string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B
6524 array | *size*: 0..23 | array | 0x80..0x97
6525 array | *size*: 23..255 | array (1 byte follow) | 0x98
6526 array | *size*: 256..65535 | array (2 bytes follow) | 0x99
6527 array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A
6528 array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B
6529 object | *size*: 0..23 | map | 0xA0..0xB7
6530 object | *size*: 23..255 | map (1 byte follow) | 0xB8
6531 object | *size*: 256..65535 | map (2 bytes follow) | 0xB9
6532 object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA
6533 object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB
6534
6535 @note The mapping is **complete** in the sense that any JSON value type
6536 can be converted to a CBOR value.
6537
6538 @note If NaN or Infinity are stored inside a JSON number, they are
6539 serialized properly. This behavior differs from the @ref dump()
6540 function which serializes NaN or Infinity to `null`.
6541
6542 @note The following CBOR types are not used in the conversion:
6543 - byte strings (0x40..0x5F)
6544 - UTF-8 strings terminated by "break" (0x7F)
6545 - arrays terminated by "break" (0x9F)
6546 - maps terminated by "break" (0xBF)
6547 - date/time (0xC0..0xC1)
6548 - bignum (0xC2..0xC3)
6549 - decimal fraction (0xC4)
6550 - bigfloat (0xC5)
6551 - tagged items (0xC6..0xD4, 0xD8..0xDB)
6552 - expected conversions (0xD5..0xD7)
6553 - simple values (0xE0..0xF3, 0xF8)
6554 - undefined (0xF7)
6555 - half and single-precision floats (0xF9-0xFA)
6556 - break (0xFF)
6557
6558 @param[in] j JSON value to serialize
6559 @return MessagePack serialization as byte vector
6560
6561 @complexity Linear in the size of the JSON value @a j.
6562
6563 @liveexample{The example shows the serialization of a JSON value to a byte
6564 vector in CBOR format.,to_cbor}
6565
6566 @sa http://cbor.io
6567 @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
6568 analogous deserialization
6569 @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
6570 @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
6571 related UBJSON format
6572
6573 @since version 2.0.9
6574 */
6575 static std::vector<uint8_t> to_cbor(const basic_json& j)
6576 {
6577 std::vector<uint8_t> result;
6578 to_cbor(j, result);
6579 return result;
6580 }
6581
6582 static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o)
6583 {
6584 binary_writer<uint8_t>(o).write_cbor(j);
6585 }
6586
6587 static void to_cbor(const basic_json& j, detail::output_adapter<char> o)
6588 {
6589 binary_writer<char>(o).write_cbor(j);
6590 }
6591
6592 /*!
6593 @brief create a MessagePack serialization of a given JSON value
6594
6595 Serializes a given JSON value @a j to a byte vector using the MessagePack
6596 serialization format. MessagePack is a binary serialization format which
6597 aims to be more compact than JSON itself, yet more efficient to parse.
6598
6599 The library uses the following mapping from JSON values types to
6600 MessagePack types according to the MessagePack specification:
6601
6602 JSON value type | value/range | MessagePack type | first byte
6603 --------------- | --------------------------------- | ---------------- | ----------
6604 null | `null` | nil | 0xC0
6605 boolean | `true` | true | 0xC3
6606 boolean | `false` | false | 0xC2
6607 number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3
6608 number_integer | -2147483648..-32769 | int32 | 0xD2
6609 number_integer | -32768..-129 | int16 | 0xD1
6610 number_integer | -128..-33 | int8 | 0xD0
6611 number_integer | -32..-1 | negative fixint | 0xE0..0xFF
6612 number_integer | 0..127 | positive fixint | 0x00..0x7F
6613 number_integer | 128..255 | uint 8 | 0xCC
6614 number_integer | 256..65535 | uint 16 | 0xCD
6615 number_integer | 65536..4294967295 | uint 32 | 0xCE
6616 number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF
6617 number_unsigned | 0..127 | positive fixint | 0x00..0x7F
6618 number_unsigned | 128..255 | uint 8 | 0xCC
6619 number_unsigned | 256..65535 | uint 16 | 0xCD
6620 number_unsigned | 65536..4294967295 | uint 32 | 0xCE
6621 number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF
6622 number_float | *any value* | float 64 | 0xCB
6623 string | *length*: 0..31 | fixstr | 0xA0..0xBF
6624 string | *length*: 32..255 | str 8 | 0xD9
6625 string | *length*: 256..65535 | str 16 | 0xDA
6626 string | *length*: 65536..4294967295 | str 32 | 0xDB
6627 array | *size*: 0..15 | fixarray | 0x90..0x9F
6628 array | *size*: 16..65535 | array 16 | 0xDC
6629 array | *size*: 65536..4294967295 | array 32 | 0xDD
6630 object | *size*: 0..15 | fix map | 0x80..0x8F
6631 object | *size*: 16..65535 | map 16 | 0xDE
6632 object | *size*: 65536..4294967295 | map 32 | 0xDF
6633
6634 @note The mapping is **complete** in the sense that any JSON value type
6635 can be converted to a MessagePack value.
6636
6637 @note The following values can **not** be converted to a MessagePack value:
6638 - strings with more than 4294967295 bytes
6639 - arrays with more than 4294967295 elements
6640 - objects with more than 4294967295 elements
6641
6642 @note The following MessagePack types are not used in the conversion:
6643 - bin 8 - bin 32 (0xC4..0xC6)
6644 - ext 8 - ext 32 (0xC7..0xC9)
6645 - float 32 (0xCA)
6646 - fixext 1 - fixext 16 (0xD4..0xD8)
6647
6648 @note Any MessagePack output created @ref to_msgpack can be successfully
6649 parsed by @ref from_msgpack.
6650
6651 @note If NaN or Infinity are stored inside a JSON number, they are
6652 serialized properly. This behavior differs from the @ref dump()
6653 function which serializes NaN or Infinity to `null`.
6654
6655 @param[in] j JSON value to serialize
6656 @return MessagePack serialization as byte vector
6657
6658 @complexity Linear in the size of the JSON value @a j.
6659
6660 @liveexample{The example shows the serialization of a JSON value to a byte
6661 vector in MessagePack format.,to_msgpack}
6662
6663 @sa http://msgpack.org
6664 @sa @ref from_msgpack for the analogous deserialization
6665 @sa @ref to_cbor(const basic_json& for the related CBOR format
6666 @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
6667 related UBJSON format
6668
6669 @since version 2.0.9
6670 */
6671 static std::vector<uint8_t> to_msgpack(const basic_json& j)
6672 {
6673 std::vector<uint8_t> result;
6674 to_msgpack(j, result);
6675 return result;
6676 }
6677
6678 static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o)
6679 {
6680 binary_writer<uint8_t>(o).write_msgpack(j);
6681 }
6682
6683 static void to_msgpack(const basic_json& j, detail::output_adapter<char> o)
6684 {
6685 binary_writer<char>(o).write_msgpack(j);
6686 }
6687
6688 /*!
6689 @brief create a UBJSON serialization of a given JSON value
6690
6691 Serializes a given JSON value @a j to a byte vector using the UBJSON
6692 (Universal Binary JSON) serialization format. UBJSON aims to be more compact
6693 than JSON itself, yet more efficient to parse.
6694
6695 The library uses the following mapping from JSON values types to
6696 UBJSON types according to the UBJSON specification:
6697
6698 JSON value type | value/range | UBJSON type | marker
6699 --------------- | --------------------------------- | ----------- | ------
6700 null | `null` | null | `Z`
6701 boolean | `true` | true | `T`
6702 boolean | `false` | false | `F`
6703 number_integer | -9223372036854775808..-2147483649 | int64 | `L`
6704 number_integer | -2147483648..-32769 | int32 | `l`
6705 number_integer | -32768..-129 | int16 | `I`
6706 number_integer | -128..127 | int8 | `i`
6707 number_integer | 128..255 | uint8 | `U`
6708 number_integer | 256..32767 | int16 | `I`
6709 number_integer | 32768..2147483647 | int32 | `l`
6710 number_integer | 2147483648..9223372036854775807 | int64 | `L`
6711 number_unsigned | 0..127 | int8 | `i`
6712 number_unsigned | 128..255 | uint8 | `U`
6713 number_unsigned | 256..32767 | int16 | `I`
6714 number_unsigned | 32768..2147483647 | int32 | `l`
6715 number_unsigned | 2147483648..9223372036854775807 | int64 | `L`
6716 number_float | *any value* | float64 | `D`
6717 string | *with shortest length indicator* | string | `S`
6718 array | *see notes on optimized format* | array | `[`
6719 object | *see notes on optimized format* | map | `{`
6720
6721 @note The mapping is **complete** in the sense that any JSON value type
6722 can be converted to a UBJSON value.
6723
6724 @note The following values can **not** be converted to a UBJSON value:
6725 - strings with more than 9223372036854775807 bytes (theoretical)
6726 - unsigned integer numbers above 9223372036854775807
6727
6728 @note The following markers are not used in the conversion:
6729 - `Z`: no-op values are not created.
6730 - `C`: single-byte strings are serialized with `S` markers.
6731
6732 @note Any UBJSON output created @ref to_ubjson can be successfully parsed
6733 by @ref from_ubjson.
6734
6735 @note If NaN or Infinity are stored inside a JSON number, they are
6736 serialized properly. This behavior differs from the @ref dump()
6737 function which serializes NaN or Infinity to `null`.
6738
6739 @note The optimized formats for containers are supported: Parameter
6740 @a use_size adds size information to the beginning of a container and
6741 removes the closing marker. Parameter @a use_type further checks
6742 whether all elements of a container have the same type and adds the
6743 type marker to the beginning of the container. The @a use_type
6744 parameter must only be used together with @a use_size = true. Note
6745 that @a use_size = true alone may result in larger representations -
6746 the benefit of this parameter is that the receiving side is
6747 immediately informed on the number of elements of the container.
6748
6749 @param[in] j JSON value to serialize
6750 @param[in] use_size whether to add size annotations to container types
6751 @param[in] use_type whether to add type annotations to container types
6752 (must be combined with @a use_size = true)
6753 @return UBJSON serialization as byte vector
6754
6755 @complexity Linear in the size of the JSON value @a j.
6756
6757 @liveexample{The example shows the serialization of a JSON value to a byte
6758 vector in UBJSON format.,to_ubjson}
6759
6760 @sa http://ubjson.org
6761 @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
6762 analogous deserialization
6763 @sa @ref to_cbor(const basic_json& for the related CBOR format
6764 @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
6765
6766 @since version 3.1.0
6767 */
6768 static std::vector<uint8_t> to_ubjson(const basic_json& j,
6769 const bool use_size = false,
6770 const bool use_type = false)
6771 {
6772 std::vector<uint8_t> result;
6773 to_ubjson(j, result, use_size, use_type);
6774 return result;
6775 }
6776
6777 static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o,
6778 const bool use_size = false, const bool use_type = false)
6779 {
6780 binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type);
6781 }
6782
6783 static void to_ubjson(const basic_json& j, detail::output_adapter<char> o,
6784 const bool use_size = false, const bool use_type = false)
6785 {
6786 binary_writer<char>(o).write_ubjson(j, use_size, use_type);
6787 }
6788
6789
6790 /*!
6791 @brief Serializes the given JSON object `j` to BSON and returns a vector
6792 containing the corresponding BSON-representation.
6793
6794 BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are
6795 stored as a single entity (a so-called document).
6796
6797 The library uses the following mapping from JSON values types to BSON types:
6798
6799 JSON value type | value/range | BSON type | marker
6800 --------------- | --------------------------------- | ----------- | ------
6801 null | `null` | null | 0x0A
6802 boolean | `true`, `false` | boolean | 0x08
6803 number_integer | -9223372036854775808..-2147483649 | int64 | 0x12
6804 number_integer | -2147483648..2147483647 | int32 | 0x10
6805 number_integer | 2147483648..9223372036854775807 | int64 | 0x12
6806 number_unsigned | 0..2147483647 | int32 | 0x10
6807 number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12
6808 number_unsigned | 9223372036854775808..18446744073709551615| -- | --
6809 number_float | *any value* | double | 0x01
6810 string | *any value* | string | 0x02
6811 array | *any value* | document | 0x04
6812 object | *any value* | document | 0x03
6813
6814 @warning The mapping is **incomplete**, since only JSON-objects (and things
6815 contained therein) can be serialized to BSON.
6816 Also, integers larger than 9223372036854775807 cannot be serialized to BSON,
6817 and the keys may not contain U+0000, since they are serialized a
6818 zero-terminated c-strings.
6819
6820 @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807`
6821 @throw out_of_range.409 if a key in `j` contains a NULL (U+0000)
6822 @throw type_error.317 if `!j.is_object()`
6823
6824 @pre The input `j` is required to be an object: `j.is_object() == true`.
6825
6826 @note Any BSON output created via @ref to_bson can be successfully parsed
6827 by @ref from_bson.
6828
6829 @param[in] j JSON value to serialize
6830 @return BSON serialization as byte vector
6831
6832 @complexity Linear in the size of the JSON value @a j.
6833
6834 @liveexample{The example shows the serialization of a JSON value to a byte
6835 vector in BSON format.,to_bson}
6836
6837 @sa http://bsonspec.org/spec.html
6838 @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the
6839 analogous deserialization
6840 @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
6841 related UBJSON format
6842 @sa @ref to_cbor(const basic_json&) for the related CBOR format
6843 @sa @ref to_msgpack(const basic_json&) for the related MessagePack format
6844 */
6845 static std::vector<uint8_t> to_bson(const basic_json& j)
6846 {
6847 std::vector<uint8_t> result;
6848 to_bson(j, result);
6849 return result;
6850 }
6851
6852 /*!
6853 @brief Serializes the given JSON object `j` to BSON and forwards the
6854 corresponding BSON-representation to the given output_adapter `o`.
6855 @param j The JSON object to convert to BSON.
6856 @param o The output adapter that receives the binary BSON representation.
6857 @pre The input `j` shall be an object: `j.is_object() == true`
6858 @sa @ref to_bson(const basic_json&)
6859 */
6860 static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o)
6861 {
6862 binary_writer<uint8_t>(o).write_bson(j);
6863 }
6864
6865 /*!
6866 @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>)
6867 */
6868 static void to_bson(const basic_json& j, detail::output_adapter<char> o)
6869 {
6870 binary_writer<char>(o).write_bson(j);
6871 }
6872
6873
6874 /*!
6875 @brief create a JSON value from an input in CBOR format
6876
6877 Deserializes a given input @a i to a JSON value using the CBOR (Concise
6878 Binary Object Representation) serialization format.
6879
6880 The library maps CBOR types to JSON value types as follows:
6881
6882 CBOR type | JSON value type | first byte
6883 ---------------------- | --------------- | ----------
6884 Integer | number_unsigned | 0x00..0x17
6885 Unsigned integer | number_unsigned | 0x18
6886 Unsigned integer | number_unsigned | 0x19
6887 Unsigned integer | number_unsigned | 0x1A
6888 Unsigned integer | number_unsigned | 0x1B
6889 Negative integer | number_integer | 0x20..0x37
6890 Negative integer | number_integer | 0x38
6891 Negative integer | number_integer | 0x39
6892 Negative integer | number_integer | 0x3A
6893 Negative integer | number_integer | 0x3B
6894 Negative integer | number_integer | 0x40..0x57
6895 UTF-8 string | string | 0x60..0x77
6896 UTF-8 string | string | 0x78
6897 UTF-8 string | string | 0x79
6898 UTF-8 string | string | 0x7A
6899 UTF-8 string | string | 0x7B
6900 UTF-8 string | string | 0x7F
6901 array | array | 0x80..0x97
6902 array | array | 0x98
6903 array | array | 0x99
6904 array | array | 0x9A
6905 array | array | 0x9B
6906 array | array | 0x9F
6907 map | object | 0xA0..0xB7
6908 map | object | 0xB8
6909 map | object | 0xB9
6910 map | object | 0xBA
6911 map | object | 0xBB
6912 map | object | 0xBF
6913 False | `false` | 0xF4
6914 True | `true` | 0xF5
6915 Null | `null` | 0xF6
6916 Half-Precision Float | number_float | 0xF9
6917 Single-Precision Float | number_float | 0xFA
6918 Double-Precision Float | number_float | 0xFB
6919
6920 @warning The mapping is **incomplete** in the sense that not all CBOR
6921 types can be converted to a JSON value. The following CBOR types
6922 are not supported and will yield parse errors (parse_error.112):
6923 - byte strings (0x40..0x5F)
6924 - date/time (0xC0..0xC1)
6925 - bignum (0xC2..0xC3)
6926 - decimal fraction (0xC4)
6927 - bigfloat (0xC5)
6928 - tagged items (0xC6..0xD4, 0xD8..0xDB)
6929 - expected conversions (0xD5..0xD7)
6930 - simple values (0xE0..0xF3, 0xF8)
6931 - undefined (0xF7)
6932
6933 @warning CBOR allows map keys of any type, whereas JSON only allows
6934 strings as keys in object values. Therefore, CBOR maps with keys
6935 other than UTF-8 strings are rejected (parse_error.113).
6936
6937 @note Any CBOR output created @ref to_cbor can be successfully parsed by
6938 @ref from_cbor.
6939
6940 @param[in] i an input in CBOR format convertible to an input adapter
6941 @param[in] strict whether to expect the input to be consumed until EOF
6942 (true by default)
6943 @param[in] allow_exceptions whether to throw exceptions in case of a
6944 parse error (optional, true by default)
6945
6946 @return deserialized JSON value; in case of a parse error and
6947 @a allow_exceptions set to `false`, the return value will be
6948 value_t::discarded.
6949
6950 @throw parse_error.110 if the given input ends prematurely or the end of
6951 file was not reached when @a strict was set to true
6952 @throw parse_error.112 if unsupported features from CBOR were
6953 used in the given input @a v or if the input is not valid CBOR
6954 @throw parse_error.113 if a string was expected as map key, but not found
6955
6956 @complexity Linear in the size of the input @a i.
6957
6958 @liveexample{The example shows the deserialization of a byte vector in CBOR
6959 format to a JSON value.,from_cbor}
6960
6961 @sa http://cbor.io
6962 @sa @ref to_cbor(const basic_json&) for the analogous serialization
6963 @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the
6964 related MessagePack format
6965 @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
6966 related UBJSON format
6967
6968 @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
6969 consume input adapters, removed start_index parameter, and added
6970 @a strict parameter since 3.0.0; added @a allow_exceptions parameter
6971 since 3.2.0
6972 */
6973 JSON_HEDLEY_WARN_UNUSED_RESULT
6974 static basic_json from_cbor(detail::input_adapter&& i,
6975 const bool strict = true,
6976 const bool allow_exceptions = true)
6977 {
6978 basic_json result;
6979 detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
6980 const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::cbor, &sdp, strict);
6981 return res ? result : basic_json(value_t::discarded);
6982 }
6983
6984 /*!
6985 @copydoc from_cbor(detail::input_adapter&&, const bool, const bool)
6986 */
6987 template<typename A1, typename A2,
6988 detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
6989 JSON_HEDLEY_WARN_UNUSED_RESULT
6990 static basic_json from_cbor(A1 && a1, A2 && a2,
6991 const bool strict = true,
6992 const bool allow_exceptions = true)
6993 {
6994 basic_json result;
6995 detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
6996 const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::cbor, &sdp, strict);
6997 return res ? result : basic_json(value_t::discarded);
6998 }
6999
7000 /*!
7001 @brief create a JSON value from an input in MessagePack format
7002
7003 Deserializes a given input @a i to a JSON value using the MessagePack
7004 serialization format.
7005
7006 The library maps MessagePack types to JSON value types as follows:
7007
7008 MessagePack type | JSON value type | first byte
7009 ---------------- | --------------- | ----------
7010 positive fixint | number_unsigned | 0x00..0x7F
7011 fixmap | object | 0x80..0x8F
7012 fixarray | array | 0x90..0x9F
7013 fixstr | string | 0xA0..0xBF
7014 nil | `null` | 0xC0
7015 false | `false` | 0xC2
7016 true | `true` | 0xC3
7017 float 32 | number_float | 0xCA
7018 float 64 | number_float | 0xCB
7019 uint 8 | number_unsigned | 0xCC
7020 uint 16 | number_unsigned | 0xCD
7021 uint 32 | number_unsigned | 0xCE
7022 uint 64 | number_unsigned | 0xCF
7023 int 8 | number_integer | 0xD0
7024 int 16 | number_integer | 0xD1
7025 int 32 | number_integer | 0xD2
7026 int 64 | number_integer | 0xD3
7027 str 8 | string | 0xD9
7028 str 16 | string | 0xDA
7029 str 32 | string | 0xDB
7030 array 16 | array | 0xDC
7031 array 32 | array | 0xDD
7032 map 16 | object | 0xDE
7033 map 32 | object | 0xDF
7034 negative fixint | number_integer | 0xE0-0xFF
7035
7036 @warning The mapping is **incomplete** in the sense that not all
7037 MessagePack types can be converted to a JSON value. The following
7038 MessagePack types are not supported and will yield parse errors:
7039 - bin 8 - bin 32 (0xC4..0xC6)
7040 - ext 8 - ext 32 (0xC7..0xC9)
7041 - fixext 1 - fixext 16 (0xD4..0xD8)
7042
7043 @note Any MessagePack output created @ref to_msgpack can be successfully
7044 parsed by @ref from_msgpack.
7045
7046 @param[in] i an input in MessagePack format convertible to an input
7047 adapter
7048 @param[in] strict whether to expect the input to be consumed until EOF
7049 (true by default)
7050 @param[in] allow_exceptions whether to throw exceptions in case of a
7051 parse error (optional, true by default)
7052
7053 @return deserialized JSON value; in case of a parse error and
7054 @a allow_exceptions set to `false`, the return value will be
7055 value_t::discarded.
7056
7057 @throw parse_error.110 if the given input ends prematurely or the end of
7058 file was not reached when @a strict was set to true
7059 @throw parse_error.112 if unsupported features from MessagePack were
7060 used in the given input @a i or if the input is not valid MessagePack
7061 @throw parse_error.113 if a string was expected as map key, but not found
7062
7063 @complexity Linear in the size of the input @a i.
7064
7065 @liveexample{The example shows the deserialization of a byte vector in
7066 MessagePack format to a JSON value.,from_msgpack}
7067
7068 @sa http://msgpack.org
7069 @sa @ref to_msgpack(const basic_json&) for the analogous serialization
7070 @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
7071 related CBOR format
7072 @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for
7073 the related UBJSON format
7074 @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
7075 the related BSON format
7076
7077 @since version 2.0.9; parameter @a start_index since 2.1.1; changed to
7078 consume input adapters, removed start_index parameter, and added
7079 @a strict parameter since 3.0.0; added @a allow_exceptions parameter
7080 since 3.2.0
7081 */
7082 JSON_HEDLEY_WARN_UNUSED_RESULT
7083 static basic_json from_msgpack(detail::input_adapter&& i,
7084 const bool strict = true,
7085 const bool allow_exceptions = true)
7086 {
7087 basic_json result;
7088 detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
7089 const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::msgpack, &sdp, strict);
7090 return res ? result : basic_json(value_t::discarded);
7091 }
7092
7093 /*!
7094 @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool)
7095 */
7096 template<typename A1, typename A2,
7097 detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
7098 JSON_HEDLEY_WARN_UNUSED_RESULT
7099 static basic_json from_msgpack(A1 && a1, A2 && a2,
7100 const bool strict = true,
7101 const bool allow_exceptions = true)
7102 {
7103 basic_json result;
7104 detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
7105 const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::msgpack, &sdp, strict);
7106 return res ? result : basic_json(value_t::discarded);
7107 }
7108
7109 /*!
7110 @brief create a JSON value from an input in UBJSON format
7111
7112 Deserializes a given input @a i to a JSON value using the UBJSON (Universal
7113 Binary JSON) serialization format.
7114
7115 The library maps UBJSON types to JSON value types as follows:
7116
7117 UBJSON type | JSON value type | marker
7118 ----------- | --------------------------------------- | ------
7119 no-op | *no value, next value is read* | `N`
7120 null | `null` | `Z`
7121 false | `false` | `F`
7122 true | `true` | `T`
7123 float32 | number_float | `d`
7124 float64 | number_float | `D`
7125 uint8 | number_unsigned | `U`
7126 int8 | number_integer | `i`
7127 int16 | number_integer | `I`
7128 int32 | number_integer | `l`
7129 int64 | number_integer | `L`
7130 string | string | `S`
7131 char | string | `C`
7132 array | array (optimized values are supported) | `[`
7133 object | object (optimized values are supported) | `{`
7134
7135 @note The mapping is **complete** in the sense that any UBJSON value can
7136 be converted to a JSON value.
7137
7138 @param[in] i an input in UBJSON format convertible to an input adapter
7139 @param[in] strict whether to expect the input to be consumed until EOF
7140 (true by default)
7141 @param[in] allow_exceptions whether to throw exceptions in case of a
7142 parse error (optional, true by default)
7143
7144 @return deserialized JSON value; in case of a parse error and
7145 @a allow_exceptions set to `false`, the return value will be
7146 value_t::discarded.
7147
7148 @throw parse_error.110 if the given input ends prematurely or the end of
7149 file was not reached when @a strict was set to true
7150 @throw parse_error.112 if a parse error occurs
7151 @throw parse_error.113 if a string could not be parsed successfully
7152
7153 @complexity Linear in the size of the input @a i.
7154
7155 @liveexample{The example shows the deserialization of a byte vector in
7156 UBJSON format to a JSON value.,from_ubjson}
7157
7158 @sa http://ubjson.org
7159 @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the
7160 analogous serialization
7161 @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
7162 related CBOR format
7163 @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
7164 the related MessagePack format
7165 @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for
7166 the related BSON format
7167
7168 @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0
7169 */
7170 JSON_HEDLEY_WARN_UNUSED_RESULT
7171 static basic_json from_ubjson(detail::input_adapter&& i,
7172 const bool strict = true,
7173 const bool allow_exceptions = true)
7174 {
7175 basic_json result;
7176 detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
7177 const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::ubjson, &sdp, strict);
7178 return res ? result : basic_json(value_t::discarded);
7179 }
7180
7181 /*!
7182 @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool)
7183 */
7184 template<typename A1, typename A2,
7185 detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
7186 JSON_HEDLEY_WARN_UNUSED_RESULT
7187 static basic_json from_ubjson(A1 && a1, A2 && a2,
7188 const bool strict = true,
7189 const bool allow_exceptions = true)
7190 {
7191 basic_json result;
7192 detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
7193 const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::ubjson, &sdp, strict);
7194 return res ? result : basic_json(value_t::discarded);
7195 }
7196
7197 /*!
7198 @brief Create a JSON value from an input in BSON format
7199
7200 Deserializes a given input @a i to a JSON value using the BSON (Binary JSON)
7201 serialization format.
7202
7203 The library maps BSON record types to JSON value types as follows:
7204
7205 BSON type | BSON marker byte | JSON value type
7206 --------------- | ---------------- | ---------------------------
7207 double | 0x01 | number_float
7208 string | 0x02 | string
7209 document | 0x03 | object
7210 array | 0x04 | array
7211 binary | 0x05 | still unsupported
7212 undefined | 0x06 | still unsupported
7213 ObjectId | 0x07 | still unsupported
7214 boolean | 0x08 | boolean
7215 UTC Date-Time | 0x09 | still unsupported
7216 null | 0x0A | null
7217 Regular Expr. | 0x0B | still unsupported
7218 DB Pointer | 0x0C | still unsupported
7219 JavaScript Code | 0x0D | still unsupported
7220 Symbol | 0x0E | still unsupported
7221 JavaScript Code | 0x0F | still unsupported
7222 int32 | 0x10 | number_integer
7223 Timestamp | 0x11 | still unsupported
7224 128-bit decimal float | 0x13 | still unsupported
7225 Max Key | 0x7F | still unsupported
7226 Min Key | 0xFF | still unsupported
7227
7228 @warning The mapping is **incomplete**. The unsupported mappings
7229 are indicated in the table above.
7230
7231 @param[in] i an input in BSON format convertible to an input adapter
7232 @param[in] strict whether to expect the input to be consumed until EOF
7233 (true by default)
7234 @param[in] allow_exceptions whether to throw exceptions in case of a
7235 parse error (optional, true by default)
7236
7237 @return deserialized JSON value; in case of a parse error and
7238 @a allow_exceptions set to `false`, the return value will be
7239 value_t::discarded.
7240
7241 @throw parse_error.114 if an unsupported BSON record type is encountered
7242
7243 @complexity Linear in the size of the input @a i.
7244
7245 @liveexample{The example shows the deserialization of a byte vector in
7246 BSON format to a JSON value.,from_bson}
7247
7248 @sa http://bsonspec.org/spec.html
7249 @sa @ref to_bson(const basic_json&) for the analogous serialization
7250 @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the
7251 related CBOR format
7252 @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for
7253 the related MessagePack format
7254 @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the
7255 related UBJSON format
7256 */
7257 JSON_HEDLEY_WARN_UNUSED_RESULT
7258 static basic_json from_bson(detail::input_adapter&& i,
7259 const bool strict = true,
7260 const bool allow_exceptions = true)
7261 {
7262 basic_json result;
7263 detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
7264 const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::bson, &sdp, strict);
7265 return res ? result : basic_json(value_t::discarded);
7266 }
7267
7268 /*!
7269 @copydoc from_bson(detail::input_adapter&&, const bool, const bool)
7270 */
7271 template<typename A1, typename A2,
7272 detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0>
7273 JSON_HEDLEY_WARN_UNUSED_RESULT
7274 static basic_json from_bson(A1 && a1, A2 && a2,
7275 const bool strict = true,
7276 const bool allow_exceptions = true)
7277 {
7278 basic_json result;
7279 detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions);
7280 const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::bson, &sdp, strict);
7281 return res ? result : basic_json(value_t::discarded);
7282 }
7283
7284
7285
7286 /// @}
7287
7288 //////////////////////////
7289 // JSON Pointer support //
7290 //////////////////////////
7291
7292 /// @name JSON Pointer functions
7293 /// @{
7294
7295 /*!
7296 @brief access specified element via JSON Pointer
7297
7298 Uses a JSON pointer to retrieve a reference to the respective JSON value.
7299 No bound checking is performed. Similar to @ref operator[](const typename
7300 object_t::key_type&), `null` values are created in arrays and objects if
7301 necessary.
7302
7303 In particular:
7304 - If the JSON pointer points to an object key that does not exist, it
7305 is created an filled with a `null` value before a reference to it
7306 is returned.
7307 - If the JSON pointer points to an array index that does not exist, it
7308 is created an filled with a `null` value before a reference to it
7309 is returned. All indices between the current maximum and the given
7310 index are also filled with `null`.
7311 - The special value `-` is treated as a synonym for the index past the
7312 end.
7313
7314 @param[in] ptr a JSON pointer
7315
7316 @return reference to the element pointed to by @a ptr
7317
7318 @complexity Constant.
7319
7320 @throw parse_error.106 if an array index begins with '0'
7321 @throw parse_error.109 if an array index was not a number
7322 @throw out_of_range.404 if the JSON pointer can not be resolved
7323
7324 @liveexample{The behavior is shown in the example.,operatorjson_pointer}
7325
7326 @since version 2.0.0
7327 */
7328 reference operator[](const json_pointer& ptr)
7329 {
7330 return ptr.get_unchecked(this);
7331 }
7332
7333 /*!
7334 @brief access specified element via JSON Pointer
7335
7336 Uses a JSON pointer to retrieve a reference to the respective JSON value.
7337 No bound checking is performed. The function does not change the JSON
7338 value; no `null` values are created. In particular, the the special value
7339 `-` yields an exception.
7340
7341 @param[in] ptr JSON pointer to the desired element
7342
7343 @return const reference to the element pointed to by @a ptr
7344
7345 @complexity Constant.
7346
7347 @throw parse_error.106 if an array index begins with '0'
7348 @throw parse_error.109 if an array index was not a number
7349 @throw out_of_range.402 if the array index '-' is used
7350 @throw out_of_range.404 if the JSON pointer can not be resolved
7351
7352 @liveexample{The behavior is shown in the example.,operatorjson_pointer_const}
7353
7354 @since version 2.0.0
7355 */
7356 const_reference operator[](const json_pointer& ptr) const
7357 {
7358 return ptr.get_unchecked(this);
7359 }
7360
7361 /*!
7362 @brief access specified element via JSON Pointer
7363
7364 Returns a reference to the element at with specified JSON pointer @a ptr,
7365 with bounds checking.
7366
7367 @param[in] ptr JSON pointer to the desired element
7368
7369 @return reference to the element pointed to by @a ptr
7370
7371 @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
7372 begins with '0'. See example below.
7373
7374 @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
7375 is not a number. See example below.
7376
7377 @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
7378 is out of range. See example below.
7379
7380 @throw out_of_range.402 if the array index '-' is used in the passed JSON
7381 pointer @a ptr. As `at` provides checked access (and no elements are
7382 implicitly inserted), the index '-' is always invalid. See example below.
7383
7384 @throw out_of_range.403 if the JSON pointer describes a key of an object
7385 which cannot be found. See example below.
7386
7387 @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
7388 See example below.
7389
7390 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
7391 changes in the JSON value.
7392
7393 @complexity Constant.
7394
7395 @since version 2.0.0
7396
7397 @liveexample{The behavior is shown in the example.,at_json_pointer}
7398 */
7399 reference at(const json_pointer& ptr)
7400 {
7401 return ptr.get_checked(this);
7402 }
7403
7404 /*!
7405 @brief access specified element via JSON Pointer
7406
7407 Returns a const reference to the element at with specified JSON pointer @a
7408 ptr, with bounds checking.
7409
7410 @param[in] ptr JSON pointer to the desired element
7411
7412 @return reference to the element pointed to by @a ptr
7413
7414 @throw parse_error.106 if an array index in the passed JSON pointer @a ptr
7415 begins with '0'. See example below.
7416
7417 @throw parse_error.109 if an array index in the passed JSON pointer @a ptr
7418 is not a number. See example below.
7419
7420 @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr
7421 is out of range. See example below.
7422
7423 @throw out_of_range.402 if the array index '-' is used in the passed JSON
7424 pointer @a ptr. As `at` provides checked access (and no elements are
7425 implicitly inserted), the index '-' is always invalid. See example below.
7426
7427 @throw out_of_range.403 if the JSON pointer describes a key of an object
7428 which cannot be found. See example below.
7429
7430 @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved.
7431 See example below.
7432
7433 @exceptionsafety Strong guarantee: if an exception is thrown, there are no
7434 changes in the JSON value.
7435
7436 @complexity Constant.
7437
7438 @since version 2.0.0
7439
7440 @liveexample{The behavior is shown in the example.,at_json_pointer_const}
7441 */
7442 const_reference at(const json_pointer& ptr) const
7443 {
7444 return ptr.get_checked(this);
7445 }
7446
7447 /*!
7448 @brief return flattened JSON value
7449
7450 The function creates a JSON object whose keys are JSON pointers (see [RFC
7451 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all
7452 primitive. The original JSON value can be restored using the @ref
7453 unflatten() function.
7454
7455 @return an object that maps JSON pointers to primitive values
7456
7457 @note Empty objects and arrays are flattened to `null` and will not be
7458 reconstructed correctly by the @ref unflatten() function.
7459
7460 @complexity Linear in the size the JSON value.
7461
7462 @liveexample{The following code shows how a JSON object is flattened to an
7463 object whose keys consist of JSON pointers.,flatten}
7464
7465 @sa @ref unflatten() for the reverse function
7466
7467 @since version 2.0.0
7468 */
7469 basic_json flatten() const
7470 {
7471 basic_json result(value_t::object);
7472 json_pointer::flatten("", *this, result);
7473 return result;
7474 }
7475
7476 /*!
7477 @brief unflatten a previously flattened JSON value
7478
7479 The function restores the arbitrary nesting of a JSON value that has been
7480 flattened before using the @ref flatten() function. The JSON value must
7481 meet certain constraints:
7482 1. The value must be an object.
7483 2. The keys must be JSON pointers (see
7484 [RFC 6901](https://tools.ietf.org/html/rfc6901))
7485 3. The mapped values must be primitive JSON types.
7486
7487 @return the original JSON from a flattened version
7488
7489 @note Empty objects and arrays are flattened by @ref flatten() to `null`
7490 values and can not unflattened to their original type. Apart from
7491 this example, for a JSON value `j`, the following is always true:
7492 `j == j.flatten().unflatten()`.
7493
7494 @complexity Linear in the size the JSON value.
7495
7496 @throw type_error.314 if value is not an object
7497 @throw type_error.315 if object values are not primitive
7498
7499 @liveexample{The following code shows how a flattened JSON object is
7500 unflattened into the original nested JSON object.,unflatten}
7501
7502 @sa @ref flatten() for the reverse function
7503
7504 @since version 2.0.0
7505 */
7506 basic_json unflatten() const
7507 {
7508 return json_pointer::unflatten(*this);
7509 }
7510
7511 /// @}
7512
7513 //////////////////////////
7514 // JSON Patch functions //
7515 //////////////////////////
7516
7517 /// @name JSON Patch functions
7518 /// @{
7519
7520 /*!
7521 @brief applies a JSON patch
7522
7523 [JSON Patch](http://jsonpatch.com) defines a JSON document structure for
7524 expressing a sequence of operations to apply to a JSON) document. With
7525 this function, a JSON Patch is applied to the current JSON value by
7526 executing all operations from the patch.
7527
7528 @param[in] json_patch JSON patch document
7529 @return patched document
7530
7531 @note The application of a patch is atomic: Either all operations succeed
7532 and the patched document is returned or an exception is thrown. In
7533 any case, the original value is not changed: the patch is applied
7534 to a copy of the value.
7535
7536 @throw parse_error.104 if the JSON patch does not consist of an array of
7537 objects
7538
7539 @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory
7540 attributes are missing); example: `"operation add must have member path"`
7541
7542 @throw out_of_range.401 if an array index is out of range.
7543
7544 @throw out_of_range.403 if a JSON pointer inside the patch could not be
7545 resolved successfully in the current JSON value; example: `"key baz not
7546 found"`
7547
7548 @throw out_of_range.405 if JSON pointer has no parent ("add", "remove",
7549 "move")
7550
7551 @throw other_error.501 if "test" operation was unsuccessful
7552
7553 @complexity Linear in the size of the JSON value and the length of the
7554 JSON patch. As usually only a fraction of the JSON value is affected by
7555 the patch, the complexity can usually be neglected.
7556
7557 @liveexample{The following code shows how a JSON patch is applied to a
7558 value.,patch}
7559
7560 @sa @ref diff -- create a JSON patch by comparing two JSON values
7561
7562 @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
7563 @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901)
7564
7565 @since version 2.0.0
7566 */
7567 basic_json patch(const basic_json& json_patch) const
7568 {
7569 // make a working copy to apply the patch to
7570 basic_json result = *this;
7571
7572 // the valid JSON Patch operations
7573 enum class patch_operations {add, remove, replace, move, copy, test, invalid};
7574
7575 const auto get_op = [](const std::string & op)
7576 {
7577 if (op == "add")
7578 {
7579 return patch_operations::add;
7580 }
7581 if (op == "remove")
7582 {
7583 return patch_operations::remove;
7584 }
7585 if (op == "replace")
7586 {
7587 return patch_operations::replace;
7588 }
7589 if (op == "move")
7590 {
7591 return patch_operations::move;
7592 }
7593 if (op == "copy")
7594 {
7595 return patch_operations::copy;
7596 }
7597 if (op == "test")
7598 {
7599 return patch_operations::test;
7600 }
7601
7602 return patch_operations::invalid;
7603 };
7604
7605 // wrapper for "add" operation; add value at ptr
7606 const auto operation_add = [&result](json_pointer & ptr, basic_json val)
7607 {
7608 // adding to the root of the target document means replacing it
7609 if (ptr.empty())
7610 {
7611 result = val;
7612 return;
7613 }
7614
7615 // make sure the top element of the pointer exists
7616 json_pointer top_pointer = ptr.top();
7617 if (top_pointer != ptr)
7618 {
7619 result.at(top_pointer);
7620 }
7621
7622 // get reference to parent of JSON pointer ptr
7623 const auto last_path = ptr.back();
7624 ptr.pop_back();
7625 basic_json& parent = result[ptr];
7626
7627 switch (parent.m_type)
7628 {
7629 case value_t::null:
7630 case value_t::object:
7631 {
7632 // use operator[] to add value
7633 parent[last_path] = val;
7634 break;
7635 }
7636
7637 case value_t::array:
7638 {
7639 if (last_path == "-")
7640 {
7641 // special case: append to back
7642 parent.push_back(val);
7643 }
7644 else
7645 {
7646 const auto idx = json_pointer::array_index(last_path);
7647 if (JSON_HEDLEY_UNLIKELY(static_cast<size_type>(idx) > parent.size()))
7648 {
7649 // avoid undefined behavior
7650 JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range"));
7651 }
7652
7653 // default case: insert add offset
7654 parent.insert(parent.begin() + static_cast<difference_type>(idx), val);
7655 }
7656 break;
7657 }
7658
7659 // if there exists a parent it cannot be primitive
7660 default: // LCOV_EXCL_LINE
7661 assert(false); // LCOV_EXCL_LINE
7662 }
7663 };
7664
7665 // wrapper for "remove" operation; remove value at ptr
7666 const auto operation_remove = [&result](json_pointer & ptr)
7667 {
7668 // get reference to parent of JSON pointer ptr
7669 const auto last_path = ptr.back();
7670 ptr.pop_back();
7671 basic_json& parent = result.at(ptr);
7672
7673 // remove child
7674 if (parent.is_object())
7675 {
7676 // perform range check
7677 auto it = parent.find(last_path);
7678 if (JSON_HEDLEY_LIKELY(it != parent.end()))
7679 {
7680 parent.erase(it);
7681 }
7682 else
7683 {
7684 JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found"));
7685 }
7686 }
7687 else if (parent.is_array())
7688 {
7689 // note erase performs range check
7690 parent.erase(static_cast<size_type>(json_pointer::array_index(last_path)));
7691 }
7692 };
7693
7694 // type check: top level value must be an array
7695 if (JSON_HEDLEY_UNLIKELY(not json_patch.is_array()))
7696 {
7697 JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
7698 }
7699
7700 // iterate and apply the operations
7701 for (const auto& val : json_patch)
7702 {
7703 // wrapper to get a value for an operation
7704 const auto get_value = [&val](const std::string & op,
7705 const std::string & member,
7706 bool string_type) -> basic_json &
7707 {
7708 // find value
7709 auto it = val.m_value.object->find(member);
7710
7711 // context-sensitive error message
7712 const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'";
7713
7714 // check if desired value is present
7715 if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end()))
7716 {
7717 JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'"));
7718 }
7719
7720 // check if result is of type string
7721 if (JSON_HEDLEY_UNLIKELY(string_type and not it->second.is_string()))
7722 {
7723 JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'"));
7724 }
7725
7726 // no error: return value
7727 return it->second;
7728 };
7729
7730 // type check: every element of the array must be an object
7731 if (JSON_HEDLEY_UNLIKELY(not val.is_object()))
7732 {
7733 JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects"));
7734 }
7735
7736 // collect mandatory members
7737 const std::string op = get_value("op", "op", true);
7738 const std::string path = get_value(op, "path", true);
7739 json_pointer ptr(path);
7740
7741 switch (get_op(op))
7742 {
7743 case patch_operations::add:
7744 {
7745 operation_add(ptr, get_value("add", "value", false));
7746 break;
7747 }
7748
7749 case patch_operations::remove:
7750 {
7751 operation_remove(ptr);
7752 break;
7753 }
7754
7755 case patch_operations::replace:
7756 {
7757 // the "path" location must exist - use at()
7758 result.at(ptr) = get_value("replace", "value", false);
7759 break;
7760 }
7761
7762 case patch_operations::move:
7763 {
7764 const std::string from_path = get_value("move", "from", true);
7765 json_pointer from_ptr(from_path);
7766
7767 // the "from" location must exist - use at()
7768 basic_json v = result.at(from_ptr);
7769
7770 // The move operation is functionally identical to a
7771 // "remove" operation on the "from" location, followed
7772 // immediately by an "add" operation at the target
7773 // location with the value that was just removed.
7774 operation_remove(from_ptr);
7775 operation_add(ptr, v);
7776 break;
7777 }
7778
7779 case patch_operations::copy:
7780 {
7781 const std::string from_path = get_value("copy", "from", true);
7782 const json_pointer from_ptr(from_path);
7783
7784 // the "from" location must exist - use at()
7785 basic_json v = result.at(from_ptr);
7786
7787 // The copy is functionally identical to an "add"
7788 // operation at the target location using the value
7789 // specified in the "from" member.
7790 operation_add(ptr, v);
7791 break;
7792 }
7793
7794 case patch_operations::test:
7795 {
7796 bool success = false;
7797 JSON_TRY
7798 {
7799 // check if "value" matches the one at "path"
7800 // the "path" location must exist - use at()
7801 success = (result.at(ptr) == get_value("test", "value", false));
7802 }
7803 JSON_INTERNAL_CATCH (out_of_range&)
7804 {
7805 // ignore out of range errors: success remains false
7806 }
7807
7808 // throw an exception if test fails
7809 if (JSON_HEDLEY_UNLIKELY(not success))
7810 {
7811 JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump()));
7812 }
7813
7814 break;
7815 }
7816
7817 default:
7818 {
7819 // op must be "add", "remove", "replace", "move", "copy", or
7820 // "test"
7821 JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid"));
7822 }
7823 }
7824 }
7825
7826 return result;
7827 }
7828
7829 /*!
7830 @brief creates a diff as a JSON patch
7831
7832 Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can
7833 be changed into the value @a target by calling @ref patch function.
7834
7835 @invariant For two JSON values @a source and @a target, the following code
7836 yields always `true`:
7837 @code {.cpp}
7838 source.patch(diff(source, target)) == target;
7839 @endcode
7840
7841 @note Currently, only `remove`, `add`, and `replace` operations are
7842 generated.
7843
7844 @param[in] source JSON value to compare from
7845 @param[in] target JSON value to compare against
7846 @param[in] path helper value to create JSON pointers
7847
7848 @return a JSON patch to convert the @a source to @a target
7849
7850 @complexity Linear in the lengths of @a source and @a target.
7851
7852 @liveexample{The following code shows how a JSON patch is created as a
7853 diff for two JSON values.,diff}
7854
7855 @sa @ref patch -- apply a JSON patch
7856 @sa @ref merge_patch -- apply a JSON Merge Patch
7857
7858 @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902)
7859
7860 @since version 2.0.0
7861 */
7862 JSON_HEDLEY_WARN_UNUSED_RESULT
7863 static basic_json diff(const basic_json& source, const basic_json& target,
7864 const std::string& path = "")
7865 {
7866 // the patch
7867 basic_json result(value_t::array);
7868
7869 // if the values are the same, return empty patch
7870 if (source == target)
7871 {
7872 return result;
7873 }
7874
7875 if (source.type() != target.type())
7876 {
7877 // different types: replace value
7878 result.push_back(
7879 {
7880 {"op", "replace"}, {"path", path}, {"value", target}
7881 });
7882 return result;
7883 }
7884
7885 switch (source.type())
7886 {
7887 case value_t::array:
7888 {
7889 // first pass: traverse common elements
7890 std::size_t i = 0;
7891 while (i < source.size() and i < target.size())
7892 {
7893 // recursive call to compare array values at index i
7894 auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i));
7895 result.insert(result.end(), temp_diff.begin(), temp_diff.end());
7896 ++i;
7897 }
7898
7899 // i now reached the end of at least one array
7900 // in a second pass, traverse the remaining elements
7901
7902 // remove my remaining elements
7903 const auto end_index = static_cast<difference_type>(result.size());
7904 while (i < source.size())
7905 {
7906 // add operations in reverse order to avoid invalid
7907 // indices
7908 result.insert(result.begin() + end_index, object(
7909 {
7910 {"op", "remove"},
7911 {"path", path + "/" + std::to_string(i)}
7912 }));
7913 ++i;
7914 }
7915
7916 // add other remaining elements
7917 while (i < target.size())
7918 {
7919 result.push_back(
7920 {
7921 {"op", "add"},
7922 {"path", path + "/" + std::to_string(i)},
7923 {"value", target[i]}
7924 });
7925 ++i;
7926 }
7927
7928 break;
7929 }
7930
7931 case value_t::object:
7932 {
7933 // first pass: traverse this object's elements
7934 for (auto it = source.cbegin(); it != source.cend(); ++it)
7935 {
7936 // escape the key name to be used in a JSON patch
7937 const auto key = json_pointer::escape(it.key());
7938
7939 if (target.find(it.key()) != target.end())
7940 {
7941 // recursive call to compare object values at key it
7942 auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key);
7943 result.insert(result.end(), temp_diff.begin(), temp_diff.end());
7944 }
7945 else
7946 {
7947 // found a key that is not in o -> remove it
7948 result.push_back(object(
7949 {
7950 {"op", "remove"}, {"path", path + "/" + key}
7951 }));
7952 }
7953 }
7954
7955 // second pass: traverse other object's elements
7956 for (auto it = target.cbegin(); it != target.cend(); ++it)
7957 {
7958 if (source.find(it.key()) == source.end())
7959 {
7960 // found a key that is not in this -> add it
7961 const auto key = json_pointer::escape(it.key());
7962 result.push_back(
7963 {
7964 {"op", "add"}, {"path", path + "/" + key},
7965 {"value", it.value()}
7966 });
7967 }
7968 }
7969
7970 break;
7971 }
7972
7973 default:
7974 {
7975 // both primitive type: replace value
7976 result.push_back(
7977 {
7978 {"op", "replace"}, {"path", path}, {"value", target}
7979 });
7980 break;
7981 }
7982 }
7983
7984 return result;
7985 }
7986
7987 /// @}
7988
7989 ////////////////////////////////
7990 // JSON Merge Patch functions //
7991 ////////////////////////////////
7992
7993 /// @name JSON Merge Patch functions
7994 /// @{
7995
7996 /*!
7997 @brief applies a JSON Merge Patch
7998
7999 The merge patch format is primarily intended for use with the HTTP PATCH
8000 method as a means of describing a set of modifications to a target
8001 resource's content. This function applies a merge patch to the current
8002 JSON value.
8003
8004 The function implements the following algorithm from Section 2 of
8005 [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396):
8006
8007 ```
8008 define MergePatch(Target, Patch):
8009 if Patch is an Object:
8010 if Target is not an Object:
8011 Target = {} // Ignore the contents and set it to an empty Object
8012 for each Name/Value pair in Patch:
8013 if Value is null:
8014 if Name exists in Target:
8015 remove the Name/Value pair from Target
8016 else:
8017 Target[Name] = MergePatch(Target[Name], Value)
8018 return Target
8019 else:
8020 return Patch
8021 ```
8022
8023 Thereby, `Target` is the current object; that is, the patch is applied to
8024 the current value.
8025
8026 @param[in] apply_patch the patch to apply
8027
8028 @complexity Linear in the lengths of @a patch.
8029
8030 @liveexample{The following code shows how a JSON Merge Patch is applied to
8031 a JSON document.,merge_patch}
8032
8033 @sa @ref patch -- apply a JSON patch
8034 @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396)
8035
8036 @since version 3.0.0
8037 */
8038 void merge_patch(const basic_json& apply_patch)
8039 {
8040 if (apply_patch.is_object())
8041 {
8042 if (not is_object())
8043 {
8044 *this = object();
8045 }
8046 for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it)
8047 {
8048 if (it.value().is_null())
8049 {
8050 erase(it.key());
8051 }
8052 else
8053 {
8054 operator[](it.key()).merge_patch(it.value());
8055 }
8056 }
8057 }
8058 else
8059 {
8060 *this = apply_patch;
8061 }
8062 }
8063
8064 /// @}
8065 };
8066
8067 /*!
8068 @brief user-defined to_string function for JSON values
8069
8070 This function implements a user-defined to_string for JSON objects.
8071
8072 @param[in] j a JSON object
8073 @return a std::string object
8074 */
8075
8076 NLOHMANN_BASIC_JSON_TPL_DECLARATION
8077 std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j)
8078 {
8079 return j.dump();
8080 }
8081 } // namespace nlohmann
8082
8083 ///////////////////////
8084 // nonmember support //
8085 ///////////////////////
8086
8087 // specialization of std::swap, and std::hash
8088 namespace std
8089 {
8090
8091 /// hash value for JSON objects
8092 template<>
8093 struct hash<nlohmann::json>
8094 {
8095 /*!
8096 @brief return a hash value for a JSON object
8097
8098 @since version 1.0.0
8099 */
8100 std::size_t operator()(const nlohmann::json& j) const
8101 {
8102 // a naive hashing via the string representation
8103 const auto& h = hash<nlohmann::json::string_t>();
8104 return h(j.dump());
8105 }
8106 };
8107
8108 /// specialization for std::less<value_t>
8109 /// @note: do not remove the space after '<',
8110 /// see https://github.com/nlohmann/json/pull/679
8111 template<>
8112 struct less<::nlohmann::detail::value_t>
8113 {
8114 /*!
8115 @brief compare two value_t enum values
8116 @since version 3.0.0
8117 */
8118 bool operator()(nlohmann::detail::value_t lhs,
8119 nlohmann::detail::value_t rhs) const noexcept
8120 {
8121 return nlohmann::detail::operator<(lhs, rhs);
8122 }
8123 };
8124
8125 /*!
8126 @brief exchanges the values of two JSON objects
8127
8128 @since version 1.0.0
8129 */
8130 template<>
8131 inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept(
8132 is_nothrow_move_constructible<nlohmann::json>::value and
8133 is_nothrow_move_assignable<nlohmann::json>::value
8134 )
8135 {
8136 j1.swap(j2);
8137 }
8138
8139 } // namespace std
8140
8141 /*!
8142 @brief user-defined string literal for JSON values
8143
8144 This operator implements a user-defined string literal for JSON objects. It
8145 can be used by adding `"_json"` to a string literal and returns a JSON object
8146 if no parse error occurred.
8147
8148 @param[in] s a string representation of a JSON object
8149 @param[in] n the length of string @a s
8150 @return a JSON object
8151
8152 @since version 1.0.0
8153 */
8154 JSON_HEDLEY_NON_NULL(1)
8155 inline nlohmann::json operator "" _json(const char* s, std::size_t n)
8156 {
8157 return nlohmann::json::parse(s, s + n);
8158 }
8159
8160 /*!
8161 @brief user-defined string literal for JSON pointer
8162
8163 This operator implements a user-defined string literal for JSON Pointers. It
8164 can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer
8165 object if no parse error occurred.
8166
8167 @param[in] s a string representation of a JSON Pointer
8168 @param[in] n the length of string @a s
8169 @return a JSON pointer object
8170
8171 @since version 2.0.0
8172 */
8173 JSON_HEDLEY_NON_NULL(1)
8174 inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n)
8175 {
8176 return nlohmann::json::json_pointer(std::string(s, n));
8177 }
8178
8179 #include <nlohmann/detail/macro_unscope.hpp>
8180
8181 #endif // INCLUDE_NLOHMANN_JSON_HPP_
8182