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