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