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