4
These pages contain the API documentation of JSON for Modern C++, a C++11
5
header-only JSON class.
7
Class @ref nlohmann::basic_json is a good entry point for the documentation.
9
@copyright The code is licensed under the [MIT
10
License](http://opensource.org/licenses/MIT):
12
Copyright © 2013-2015 Niels Lohmann.
14
Permission is hereby granted, free of charge, to any person obtaining a copy
15
of this software and associated documentation files (the "Software"), to deal
16
in the Software without restriction, including without limitation the rights
17
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
copies of the Software, and to permit persons to whom the Software is
19
furnished to do so, subject to the following conditions:
21
The above copyright notice and this permission notice shall be included in
22
all copies or substantial portions of the Software.
24
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32
@author [Niels Lohmann](http://nlohmann.me)
33
@see https://github.com/nlohmann/json to download the source code
38
#ifndef NLOHMANN_JSON_HPP
39
#define NLOHMANN_JSON_HPP
47
#include <initializer_list>
56
#include <type_traits>
60
// enable ssize_t on MinGW
63
#include <sys/types.h>
67
// enable ssize_t for MSVC
70
using ssize_t = SSIZE_T;
74
@brief namespace for Niels Lohmann
75
@see https://github.com/nlohmann
83
@brief unnamed namespace with internal helper functions
89
@brief Helper to determine whether there's a key_type for T.
90
@sa http://stackoverflow.com/a/7728728/266378
93
struct has_mapped_type
96
template<typename C> static char test(typename C::mapped_type*);
97
template<typename C> static int test(...);
99
enum { value = sizeof(test<T>(0)) == sizeof(char) };
102
/// "equality" comparison for floating point numbers
104
static bool approx(const T a, const T b)
106
return not (a > b or a < b);
111
@brief a class to store JSON values
113
@tparam ObjectType type for JSON objects (@c std::map by default; will be used
115
@tparam ArrayType type for JSON arrays (@c std::vector by default; will be used
117
@tparam StringType type for JSON strings and object keys (@c std::string by
118
default; will be used in @ref string_t)
119
@tparam BooleanType type for JSON booleans (@c `bool` by default; will be used
121
@tparam NumberIntegerType type for JSON integer numbers (@c `int64_t` by
122
default; will be used in @ref number_integer_t)
123
@tparam NumberFloatType type for JSON floating-point numbers (@c `double` by
124
default; will be used in @ref number_float_t)
125
@tparam AllocatorType type of the allocator to use (@c `std::allocator` by
128
@requirement The class satisfies the following concept requirements:
130
- [DefaultConstructible](http://en.cppreference.com/w/cpp/concept/DefaultConstructible):
131
JSON values can be default constructed. The result will be a JSON null value.
132
- [MoveConstructible](http://en.cppreference.com/w/cpp/concept/MoveConstructible):
133
A JSON value can be constructed from an rvalue argument.
134
- [CopyConstructible](http://en.cppreference.com/w/cpp/concept/CopyConstructible):
135
A JSON value can be copy-constrcuted from an lvalue expression.
136
- [MoveAssignable](http://en.cppreference.com/w/cpp/concept/MoveAssignable):
137
A JSON value van be assigned from an rvalue argument.
138
- [CopyAssignable](http://en.cppreference.com/w/cpp/concept/CopyAssignable):
139
A JSON value can be copy-assigned from an lvalue expression.
140
- [Destructible](http://en.cppreference.com/w/cpp/concept/Destructible):
141
JSON values can be destructed.
143
- [StandardLayoutType](http://en.cppreference.com/w/cpp/concept/StandardLayoutType):
145
[standard layout](http://en.cppreference.com/w/cpp/language/data_members#Standard_layout):
146
All non-static data members are private and standard layout types, the class
147
has no virtual functions or (virtual) base classes.
149
- [EqualityComparable](http://en.cppreference.com/w/cpp/concept/EqualityComparable):
150
JSON values can be compared with `==`, see @ref
151
operator==(const_reference,const_reference).
152
- [LessThanComparable](http://en.cppreference.com/w/cpp/concept/LessThanComparable):
153
JSON values can be compared with `<`, see @ref
154
operator<(const_reference,const_reference).
155
- [Swappable](http://en.cppreference.com/w/cpp/concept/Swappable):
156
Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of
157
other compatible types, using unqualified function call @ref swap().
158
- [NullablePointer](http://en.cppreference.com/w/cpp/concept/NullablePointer):
159
JSON values can be compared against `std::nullptr_t` objects which are used
160
to model the `null` value.
162
- [Container](http://en.cppreference.com/w/cpp/concept/Container):
163
JSON values can be used like STL containers and provide iterator access.
164
- [ReversibleContainer](http://en.cppreference.com/w/cpp/concept/ReversibleContainer);
165
JSON values can be used like STL containers and provide reverse iterator
169
@note ObjectType trick from http://stackoverflow.com/a/9860911
172
@see RFC 7159 <http://rfc7159.net/rfc7159>
179
template<typename U, typename V, typename... Args> class ObjectType = std::map,
180
template<typename U, typename... Args> class ArrayType = std::vector,
181
class StringType = std::string,
182
class BooleanType = bool,
183
class NumberIntegerType = int64_t,
184
class NumberFloatType = double,
185
template<typename U> class AllocatorType = std::allocator
190
/// workaround type for MSVC
191
using basic_json_t = basic_json<ObjectType,
201
/////////////////////
202
// container types //
203
/////////////////////
205
/// @name container types
208
/// the type of elements in a basic_json container
209
using value_type = basic_json;
211
/// the type of an element reference
212
using reference = value_type&;
214
/// the type of an element const reference
215
using const_reference = const value_type&;
217
/// a type to represent differences between iterators
218
using difference_type = std::ptrdiff_t;
220
/// a type to represent container sizes
221
using size_type = std::size_t;
223
/// the allocator type
224
using allocator_type = AllocatorType<basic_json>;
226
/// the type of an element pointer
227
using pointer = typename std::allocator_traits<allocator_type>::pointer;
228
/// the type of an element const pointer
229
using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
231
// forward declaration
232
template<typename Base> class json_reverse_iterator;
234
/// an iterator for a basic_json container
236
/// a const iterator for a basic_json container
237
class const_iterator;
238
/// a reverse iterator for a basic_json container
239
using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>;
240
/// a const reverse iterator for a basic_json container
241
using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>;
247
@brief returns the allocator associated with the container
249
static allocator_type get_allocator()
251
return allocator_type();
255
///////////////////////////
256
// JSON value data types //
257
///////////////////////////
259
/// @name JSON value data types
263
@brief a type for an object
265
[RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows:
266
> An object is an unordered collection of zero or more name/value pairs,
267
> where a name is a string and a value is a string, number, boolean, null,
270
To store objects in C++, a type is defined by the template parameters
273
@tparam ObjectType the container to store objects (e.g., `std::map` or
274
`std::unordered_map`)
275
@tparam StringType the type of the keys or names (e.g., `std::string`). The
276
comparison function `std::less<StringType>` is used to order elements
277
inside the container.
278
@tparam AllocatorType the allocator to use for objects (e.g.,
283
With the default values for @a ObjectType (`std::map`), @a StringType
284
(`std::string`), and @a AllocatorType (`std::allocator`), the default value
289
std::string, // key_type
290
basic_json, // value_type
291
std::less<std::string>, // key_compare
292
std::allocator<std::pair<const std::string, basic_json>> // allocator_type
298
The choice of @a object_t influences the behavior of the JSON class. With
299
the default type, objects have the following behavior:
301
- When all names are unique, objects will be interoperable in the sense
302
that all software implementations receiving that object will agree on the
304
- When the names within an object are not unique, later stored name/value
305
pairs overwrite previously stored name/value pairs, leaving the used
306
names unique. For instance, `{"key": 1}` and `{"key": 2, "key": 1}` will
307
be treated as equal and both stored as `{"key": 1}`.
308
- Internally, name/value pairs are stored in lexicographical order of the
309
names. Objects will also be serialized (see @ref dump) in this order. For
310
instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored and
311
serialized as `{"a": 2, "b": 1}`.
312
- When comparing objects, the order of the name/value pairs is irrelevant.
313
This makes objects interoperable in the sense that they will not be
314
affected by these differences. For instance, `{"b": 1, "a": 2}` and
315
`{"a": 2, "b": 1}` will be treated as equal.
319
[RFC 7159](http://rfc7159.net/rfc7159) specifies:
320
> An implementation may set limits on the maximum depth of nesting.
322
In this class, the object's limit of nesting is not constraint explicitly.
323
However, a maximum depth of nesting may be introduced by the compiler or
324
runtime environment. A theoretical limit can be queried by calling the @ref
325
max_size function of a JSON object.
329
Objects are stored as pointers in a @ref basic_json type. That is, for any
330
access to object values, a pointer of type `object_t*` must be dereferenced.
332
@sa @ref array_t -- type for an array value
336
using object_t = ObjectType<StringType,
338
std::less<StringType>,
339
AllocatorType<std::pair<const StringType,
343
@brief a type for an array
345
[RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows:
346
> An array is an ordered sequence of zero or more values.
348
To store objects in C++, a type is defined by the template parameters
351
@tparam ArrayType container type to store arrays (e.g., `std::vector` or
353
@tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`)
357
With the default values for @a ArrayType (`std::vector`) and @a
358
AllocatorType (`std::allocator`), the default value for @a array_t is:
362
basic_json, // value_type
363
std::allocator<basic_json> // allocator_type
369
[RFC 7159](http://rfc7159.net/rfc7159) specifies:
370
> An implementation may set limits on the maximum depth of nesting.
372
In this class, the array's limit of nesting is not constraint explicitly.
373
However, a maximum depth of nesting may be introduced by the compiler or
374
runtime environment. A theoretical limit can be queried by calling the @ref
375
max_size function of a JSON array.
379
Arrays are stored as pointers in a @ref basic_json type. That is, for any
380
access to array values, a pointer of type `array_t*` must be dereferenced.
382
@sa @ref object_t -- type for an object value
386
using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;
389
@brief a type for a string
391
[RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows:
392
> A string is a sequence of zero or more Unicode characters.
394
To store objects in C++, a type is defined by the template parameter
395
described below. Unicode values are split by the JSON class into byte-sized
396
characters during deserialization.
398
@tparam StringType the container to store strings (e.g., `std::string`).
399
Note this container is used for keys/names in objects, see @ref object_t.
403
With the default values for @a StringType (`std::string`), the default
404
value for @a string_t is:
410
#### String comparison
412
[RFC 7159](http://rfc7159.net/rfc7159) states:
413
> Software implementations are typically required to test names of object
414
> members for equality. Implementations that transform the textual
415
> representation into sequences of Unicode code units and then perform the
416
> comparison numerically, code unit by code unit, are interoperable in the
417
> sense that implementations will agree in all cases on equality or
418
> inequality of two strings. For example, implementations that compare
419
> strings with escaped characters unconverted may incorrectly find that
420
> `"a\\b"` and `"a\u005Cb"` are not equal.
422
This implementation is interoperable as it does compare strings code unit
427
String values are stored as pointers in a @ref basic_json type. That is,
428
for any access to string values, a pointer of type `string_t*` must be
433
using string_t = StringType;
436
@brief a type for a boolean
438
[RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a
439
type which differentiates the two literals `true` and `false`.
441
To store objects in C++, a type is defined by the template parameter @a
442
BooleanType which chooses the type to use.
446
With the default values for @a BooleanType (`bool`), the default value for
455
Boolean values are stored directly inside a @ref basic_json type.
459
using boolean_t = BooleanType;
462
@brief a type for a number (integer)
464
[RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
465
> The representation of numbers is similar to that used in most programming
466
> languages. A number is represented in base 10 using decimal digits. It
467
> contains an integer component that may be prefixed with an optional minus
468
> sign, which may be followed by a fraction part and/or an exponent part.
469
> Leading zeros are not allowed. (...) Numeric values that cannot be
470
> represented in the grammar below (such as Infinity and NaN) are not
473
This description includes both integer and floating-point numbers. However,
474
C++ allows more precise storage if it is known whether the number is an
475
integer or a floating-point number. Therefore, two different types, @ref
476
number_integer_t and @ref number_float_t are used.
478
To store integer numbers in C++, a type is defined by the template
479
parameter @a NumberIntegerType which chooses the type to use.
483
With the default values for @a NumberIntegerType (`int64_t`), the default
484
value for @a number_integer_t is:
490
#### Default behavior
492
- The restrictions about leading zeros is not enforced in C++. Instead,
493
leading zeros in integer literals lead to an interpretation as octal
494
number. Internally, the value will be stored as decimal number. For
495
instance, the C++ integer literal `010` will be serialized to `8`. During
496
deserialization, leading zeros yield an error.
497
- Not-a-number (NaN) values will be serialized to `null`.
501
[RFC 7159](http://rfc7159.net/rfc7159) specifies:
502
> An implementation may set limits on the range and precision of numbers.
504
When the default type is used, the maximal integer number that can be
505
stored is `9223372036854775807` (INT64_MAX) and the minimal integer number
506
that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers
507
that are out of range will yield over/underflow when used in a constructor.
508
During deserialization, too large or small integer numbers will be
509
automatically be stored as @ref number_float_t.
511
[RFC 7159](http://rfc7159.net/rfc7159) further states:
512
> Note that when such software is used, numbers that are integers and are
513
> in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense
514
> that implementations will agree exactly on their numeric values.
516
As this range is a subrange of the exactly supported range [INT64_MIN,
517
INT64_MAX], this class's integer type is interoperable.
521
Integer number values are stored directly inside a @ref basic_json type.
523
@sa @ref number_float_t -- type for number values (floating-point)
527
using number_integer_t = NumberIntegerType;
530
@brief a type for a number (floating-point)
532
[RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows:
533
> The representation of numbers is similar to that used in most programming
534
> languages. A number is represented in base 10 using decimal digits. It
535
> contains an integer component that may be prefixed with an optional minus
536
> sign, which may be followed by a fraction part and/or an exponent part.
537
> Leading zeros are not allowed. (...) Numeric values that cannot be
538
> represented in the grammar below (such as Infinity and NaN) are not
541
This description includes both integer and floating-point numbers. However,
542
C++ allows more precise storage if it is known whether the number is an
543
integer or a floating-point number. Therefore, two different types, @ref
544
number_integer_t and @ref number_float_t are used.
546
To store floating-point numbers in C++, a type is defined by the template
547
parameter @a NumberFloatType which chooses the type to use.
551
With the default values for @a NumberFloatType (`double`), the default
552
value for @a number_float_t is:
558
#### Default behavior
560
- The restrictions about leading zeros is not enforced in C++. Instead,
561
leading zeros in floating-point literals will be ignored. Internally, the
562
value will be stored as decimal number. For instance, the C++
563
floating-point literal `01.2` will be serialized to `1.2`. During
564
deserialization, leading zeros yield an error.
565
- Not-a-number (NaN) values will be serialized to `null`.
569
[RFC 7159](http://rfc7159.net/rfc7159) states:
570
> This specification allows implementations to set limits on the range and
571
> precision of numbers accepted. Since software that implements IEEE
572
> 754-2008 binary64 (double precision) numbers is generally available and
573
> widely used, good interoperability can be achieved by implementations that
574
> expect no more precision or range than these provide, in the sense that
575
> implementations will approximate JSON numbers within the expected
578
This implementation does exactly follow this approach, as it uses double
579
precision floating-point numbers. Note values smaller than
580
`-1.79769313486232e+308` and values greather than `1.79769313486232e+308`
581
will be stored as NaN internally and be serialized to `null`.
585
Floating-point number values are stored directly inside a @ref basic_json
588
@sa @ref number_integer_t -- type for number values (integer)
592
using number_float_t = NumberFloatType;
597
///////////////////////////
598
// JSON type enumeration //
599
///////////////////////////
602
@brief the JSON type enumeration
604
This enumeration collects the different JSON types. It is internally used
605
to distinguish the stored values, and the functions @ref is_null(), @ref
606
is_object(), @ref is_array(), @ref is_string(), @ref is_boolean(), @ref
607
is_number(), and @ref is_discarded() rely on it.
611
enum class value_t : uint8_t
613
null, ///< null value
614
object, ///< object (unordered set of name/value pairs)
615
array, ///< array (ordered collection of values)
616
string, ///< string value
617
boolean, ///< boolean value
618
number_integer, ///< number value (integer)
619
number_float, ///< number value (floating-point)
620
discarded ///< discarded by the the parser callback function
625
/// helper for exception-safe object creation
626
template<typename T, typename... Args>
627
static T* create(Args&& ... args)
629
AllocatorType<T> alloc;
630
auto deleter = [&](T * object)
632
alloc.deallocate(object, 1);
634
std::unique_ptr<T, decltype(deleter)> object(alloc.allocate(1), deleter);
635
alloc.construct(object.get(), std::forward<Args>(args)...);
636
return object.release();
639
////////////////////////
640
// JSON value storage //
641
////////////////////////
646
The actual storage for a JSON value of the @ref basic_json class.
652
/// object (stored with pointer to save storage)
654
/// array (stored with pointer to save storage)
656
/// string (stored with pointer to save storage)
661
number_integer_t number_integer;
662
/// number (floating-point)
663
number_float_t number_float;
665
/// default constructor (for null values)
666
json_value() noexcept = default;
667
/// constructor for booleans
668
json_value(boolean_t v) noexcept : boolean(v) {}
669
/// constructor for numbers (integer)
670
json_value(number_integer_t v) noexcept : number_integer(v) {}
671
/// constructor for numbers (floating-point)
672
json_value(number_float_t v) noexcept : number_float(v) {}
673
/// constructor for empty values of a given type
674
json_value(value_t t)
678
case value_t::object:
680
object = create<object_t>();
686
array = create<array_t>();
690
case value_t::string:
692
string = create<string_t>("");
696
case value_t::boolean:
698
boolean = boolean_t(false);
702
case value_t::number_integer:
704
number_integer = number_integer_t(0);
708
case value_t::number_float:
710
number_float = number_float_t(0.0);
721
/// constructor for strings
722
json_value(const string_t& value)
724
string = create<string_t>(value);
727
/// constructor for objects
728
json_value(const object_t& value)
730
object = create<object_t>(value);
733
/// constructor for arrays
734
json_value(const array_t& value)
736
array = create<array_t>(value);
742
//////////////////////////
743
// JSON parser callback //
744
//////////////////////////
747
@brief JSON callback events
749
This enumeration lists the parser events that can trigger calling a
750
callback function of type @ref parser_callback_t during parsing.
754
enum class parse_event_t : uint8_t
756
/// the parser read `{` and started to process a JSON object
758
/// the parser read `}` and finished processing a JSON object
760
/// the parser read `[` and started to process a JSON array
762
/// the parser read `]` and finished processing a JSON array
764
/// the parser read a key of a value in an object
766
/// the parser finished reading a JSON value
771
@brief per-element parser callback type
773
With a parser callback function, the result of parsing a JSON text can be
774
influenced. When passed to @ref parse(std::istream&, parser_callback_t) or
775
@ref parse(const string_t&, parser_callback_t), it is called on certain
776
events (passed as @ref parse_event_t via parameter @a event) with a set
777
recursion depth @a depth and context JSON value @a parsed. The return value
778
of the callback function is a boolean indicating whether the element that
779
emitted the callback shall be kept or not.
781
We distinguish six scenarios (determined by the event type) in which the
782
callback function can be called. The following table describes the values
783
of the parameters @a depth, @a event, and @a parsed.
785
parameter @a event | description | parameter @a depth | parameter @a parsed
786
------------------ | ----------- | ------------------ | -------------------
787
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
788
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
789
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
790
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
791
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
792
parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value
794
Discarding a value (i.e., returning `false`) has different effects
795
depending on the context in which function was called:
797
- Discarded values in structured types are skipped. That is, the parser
798
will behave as if the discarded value was never read.
799
- In case a value outside a structured type is skipped, it is replaced with
800
`null`. This case happens if the top-level element is skipped.
802
@param[in] depth the depth of the recursion during parsing
804
@param[in] event an event of type parse_event_t indicating the context in
805
the callback function has been called
807
@param[in,out] parsed the current intermediate parse result; note that
808
writing to this value has no effect for parse_event_t::key events
810
@return Whether the JSON value which called the function during parsing
811
should be kept (`true`) or not (`false`). In the latter case, it is either
812
skipped completely or replaced by an empty discarded object.
814
@sa @ref parse(std::istream&, parser_callback_t) or
815
@ref parse(const string_t&, parser_callback_t) for examples
819
using parser_callback_t = std::function<bool(int depth, parse_event_t event, basic_json& parsed)>;
826
/// @name constructors and destructors
830
@brief create an empty value with a given type
832
Create an empty JSON value with a given type. The value will be default
833
initialized with an empty value which depends on the type:
835
Value type | initial value
836
----------- | -------------
844
@param[in] value_type the type of the value to create
846
@complexity Constant.
848
@throw std::bad_alloc if allocation for object, array, or string value
851
@liveexample{The following code shows the constructor for different @ref
852
value_t values,basic_json__value_t}
854
@sa @ref basic_json(std::nullptr_t) -- create a `null` value
855
@sa @ref basic_json(boolean_t value) -- create a boolean value
856
@sa @ref basic_json(const string_t&) -- create a string value
857
@sa @ref basic_json(const object_t&) -- create a object value
858
@sa @ref basic_json(const array_t&) -- create a array value
859
@sa @ref basic_json(const number_float_t) -- create a number
860
(floating-point) value
861
@sa @ref basic_json(const number_integer_t) -- create a number (integer)
866
basic_json(const value_t value_type)
867
: m_type(value_type), m_value(value_type)
871
@brief create a null object (implicitly)
873
Create a `null` JSON value. This is the implicit version of the `null`
874
value constructor as it takes no parameters.
876
@complexity Constant.
878
@requirement This function satisfies the Container requirements:
879
- The complexity is constant.
880
- As postcondition, it holds: `basic_json().empty() == true`.
882
@liveexample{The following code shows the constructor for a `null` JSON
885
@sa @ref basic_json(std::nullptr_t) -- create a `null` value
889
basic_json() noexcept = default;
892
@brief create a null object (explicitly)
894
Create a `null` JSON value. This is the explicitly version of the `null`
895
value constructor as it takes a null pointer as parameter. It allows to
896
create `null` values by explicitly assigning a @c nullptr to a JSON value.
897
The passed null pointer itself is not read -- it is only used to choose the
900
@complexity Constant.
902
@liveexample{The following code shows the constructor with null pointer
903
parameter.,basic_json__nullptr_t}
905
@sa @ref basic_json() -- default constructor (implicitly creating a `null`
910
basic_json(std::nullptr_t) noexcept
911
: basic_json(value_t::null)
915
@brief create an object (explicit)
917
Create an object JSON value with a given content.
919
@param[in] val a value for the object
921
@complexity Linear in the size of the passed @a val.
923
@throw std::bad_alloc if allocation for object value fails
925
@liveexample{The following code shows the constructor with an @ref object_t
926
parameter.,basic_json__object_t}
928
@sa @ref basic_json(const CompatibleObjectType&) -- create an object value
929
from a compatible STL container
933
basic_json(const object_t& val)
934
: m_type(value_t::object), m_value(val)
938
@brief create an object (implicit)
940
Create an object JSON value with a given content. This constructor allows
941
any type that can be used to construct values of type @ref object_t.
942
Examples include the types `std::map` and `std::unordered_map`.
944
@tparam CompatibleObjectType an object type whose `key_type` and
945
`value_type` is compatible to @ref object_t
947
@param[in] val a value for the object
949
@complexity Linear in the size of the passed @a val.
951
@throw std::bad_alloc if allocation for object value fails
953
@liveexample{The following code shows the constructor with several
954
compatible object type parameters.,basic_json__CompatibleObjectType}
956
@sa @ref basic_json(const object_t&) -- create an object value
960
template <class CompatibleObjectType, typename
962
std::is_constructible<typename object_t::key_type, typename CompatibleObjectType::key_type>::value and
963
std::is_constructible<basic_json, typename CompatibleObjectType::mapped_type>::value, int>::type
965
basic_json(const CompatibleObjectType& val)
966
: m_type(value_t::object)
970
m_value.object = create<object_t>(begin(val), end(val));
974
@brief create an array (explicit)
976
Create an array JSON value with a given content.
978
@param[in] val a value for the array
980
@complexity Linear in the size of the passed @a val.
982
@throw std::bad_alloc if allocation for array value fails
984
@liveexample{The following code shows the constructor with an @ref array_t
985
parameter.,basic_json__array_t}
987
@sa @ref basic_json(const CompatibleArrayType&) -- create an array value
988
from a compatible STL containers
992
basic_json(const array_t& val)
993
: m_type(value_t::array), m_value(val)
997
@brief create an array (implicit)
999
Create an array JSON value with a given content. This constructor allows
1000
any type that can be used to construct values of type @ref array_t.
1001
Examples include the types `std::vector`, `std::list`, and `std::set`.
1003
@tparam CompatibleArrayType an object type whose `value_type` is compatible
1006
@param[in] val a value for the array
1008
@complexity Linear in the size of the passed @a val.
1010
@throw std::bad_alloc if allocation for array value fails
1012
@liveexample{The following code shows the constructor with several
1013
compatible array type parameters.,basic_json__CompatibleArrayType}
1015
@sa @ref basic_json(const array_t&) -- create an array value
1017
@since version 1.0.0
1019
template <class CompatibleArrayType, typename
1021
not std::is_same<CompatibleArrayType, typename basic_json_t::iterator>::value and
1022
not std::is_same<CompatibleArrayType, typename basic_json_t::const_iterator>::value and
1023
not std::is_same<CompatibleArrayType, typename basic_json_t::reverse_iterator>::value and
1024
not std::is_same<CompatibleArrayType, typename basic_json_t::const_reverse_iterator>::value and
1025
not std::is_same<CompatibleArrayType, typename array_t::iterator>::value and
1026
not std::is_same<CompatibleArrayType, typename array_t::const_iterator>::value and
1027
std::is_constructible<basic_json, typename CompatibleArrayType::value_type>::value, int>::type
1029
basic_json(const CompatibleArrayType& val)
1030
: m_type(value_t::array)
1034
m_value.array = create<array_t>(begin(val), end(val));
1038
@brief create a string (explicit)
1040
Create an string JSON value with a given content.
1042
@param[in] val a value for the string
1044
@complexity Linear in the size of the passed @a val.
1046
@throw std::bad_alloc if allocation for string value fails
1048
@liveexample{The following code shows the constructor with an @ref string_t
1049
parameter.,basic_json__string_t}
1051
@sa @ref basic_json(const typename string_t::value_type*) -- create a
1052
string value from a character pointer
1053
@sa @ref basic_json(const CompatibleStringType&) -- create a string value
1054
from a compatible string container
1056
@since version 1.0.0
1058
basic_json(const string_t& val)
1059
: m_type(value_t::string), m_value(val)
1063
@brief create a string (explicit)
1065
Create a string JSON value with a given content.
1067
@param[in] val a literal value for the string
1069
@complexity Linear in the size of the passed @a val.
1071
@throw std::bad_alloc if allocation for string value fails
1073
@liveexample{The following code shows the constructor with string literal
1074
parameter.,basic_json__string_t_value_type}
1076
@sa @ref basic_json(const string_t&) -- create a string value
1077
@sa @ref basic_json(const CompatibleStringType&) -- create a string value
1078
from a compatible string container
1080
@since version 1.0.0
1082
basic_json(const typename string_t::value_type* val)
1083
: basic_json(string_t(val))
1087
@brief create a string (implicit)
1089
Create a string JSON value with a given content.
1091
@param[in] val a value for the string
1093
@tparam CompatibleStringType an string type which is compatible to @ref
1096
@complexity Linear in the size of the passed @a val.
1098
@throw std::bad_alloc if allocation for string value fails
1100
@liveexample{The following code shows the construction of a string value
1101
from a compatible type.,basic_json__CompatibleStringType}
1103
@sa @ref basic_json(const string_t&) -- create a string value
1104
@sa @ref basic_json(const typename string_t::value_type*) -- create a
1105
string value from a character pointer
1107
@since version 1.0.0
1109
template <class CompatibleStringType, typename
1111
std::is_constructible<string_t, CompatibleStringType>::value, int>::type
1113
basic_json(const CompatibleStringType& val)
1114
: basic_json(string_t(val))
1118
@brief create a boolean (explicit)
1120
Creates a JSON boolean type from a given value.
1122
@param[in] val a boolean value to store
1124
@complexity Constant.
1126
@liveexample{The example below demonstrates boolean
1127
values.,basic_json__boolean_t}
1129
@since version 1.0.0
1131
basic_json(boolean_t val)
1132
: m_type(value_t::boolean), m_value(val)
1136
@brief create an integer number (explicit)
1138
Create an interger number JSON value with a given content.
1140
@tparam T helper type to compare number_integer_t and int (not visible in)
1143
@param[in] val an integer to create a JSON number from
1145
@note This constructor would have the same signature as @ref
1146
basic_json(const int value), so we need to switch this one off in case
1147
number_integer_t is the same as int. This is done via the helper type @a T.
1149
@complexity Constant.
1151
@liveexample{The example below shows the construction of a JSON integer
1152
number value.,basic_json__number_integer_t}
1154
@sa @ref basic_json(const int) -- create a number value (integer)
1155
@sa @ref basic_json(const CompatibleNumberIntegerType) -- create a number
1156
value (integer) from a compatible number type
1158
@since version 1.0.0
1160
template<typename T,
1161
typename std::enable_if<
1162
not (std::is_same<T, int>::value)
1163
and std::is_same<T, number_integer_t>::value
1165
basic_json(const number_integer_t val)
1166
: m_type(value_t::number_integer), m_value(val)
1170
@brief create an integer number from an enum type (explicit)
1172
Create an integer number JSON value with a given content.
1174
@param[in] val an integer to create a JSON number from
1176
@note This constructor allows to pass enums directly to a constructor. As
1177
C++ has no way of specifying the type of an anonymous enum explicitly, we
1178
can only rely on the fact that such values implicitly convert to int. As
1179
int may already be the same type of number_integer_t, we may need to switch
1180
off the constructor @ref basic_json(const number_integer_t).
1182
@complexity Constant.
1184
@liveexample{The example below shows the construction of a JSON integer
1185
number value from an anonymous enum.,basic_json__const_int}
1187
@sa @ref basic_json(const number_integer_t) -- create a number value
1189
@sa @ref basic_json(const CompatibleNumberIntegerType) -- create a number
1190
value (integer) from a compatible number type
1192
@since version 1.0.0
1194
basic_json(const int val)
1195
: m_type(value_t::number_integer),
1196
m_value(static_cast<number_integer_t>(val))
1200
@brief create an integer number (implicit)
1202
Create an integer number JSON value with a given content. This constructor
1203
allows any type that can be used to construct values of type @ref
1204
number_integer_t. Examples may include the types `int`, `int32_t`, or
1207
@tparam CompatibleNumberIntegerType an integer type which is compatible to
1208
@ref number_integer_t.
1210
@param[in] val an integer to create a JSON number from
1212
@complexity Constant.
1214
@liveexample{The example below shows the construction of several JSON
1215
integer number values from compatible
1216
types.,basic_json__CompatibleIntegerNumberType}
1218
@sa @ref basic_json(const number_integer_t) -- create a number value
1220
@sa @ref basic_json(const int) -- create a number value (integer)
1222
@since version 1.0.0
1224
template<typename CompatibleNumberIntegerType, typename
1226
std::is_constructible<number_integer_t, CompatibleNumberIntegerType>::value and
1227
std::numeric_limits<CompatibleNumberIntegerType>::is_integer, CompatibleNumberIntegerType>::type
1229
basic_json(const CompatibleNumberIntegerType val) noexcept
1230
: m_type(value_t::number_integer),
1231
m_value(static_cast<number_integer_t>(val))
1235
@brief create a floating-point number (explicit)
1237
Create a floating-point number JSON value with a given content.
1239
@param[in] val a floating-point value to create a JSON number from
1241
@note RFC 7159 <http://www.rfc-editor.org/rfc/rfc7159.txt>, section 6
1242
disallows NaN values:
1243
> Numeric values that cannot be represented in the grammar below (such
1244
> as Infinity and NaN) are not permitted.
1245
In case the parameter @a val is not a number, a JSON null value is
1248
@complexity Constant.
1250
@liveexample{The following example creates several floating-point
1251
values.,basic_json__number_float_t}
1253
@sa @ref basic_json(const CompatibleNumberFloatType) -- create a number
1254
value (floating-point) from a compatible number type
1256
@since version 1.0.0
1258
basic_json(const number_float_t val)
1259
: m_type(value_t::number_float), m_value(val)
1261
// replace infinity and NAN by null
1262
if (not std::isfinite(val))
1264
m_type = value_t::null;
1265
m_value = json_value();
1270
@brief create an floating-point number (implicit)
1272
Create an floating-point number JSON value with a given content. This
1273
constructor allows any type that can be used to construct values of type
1274
@ref number_float_t. Examples may include the types `float`.
1276
@tparam CompatibleNumberFloatType a floating-point type which is compatible
1277
to @ref number_float_t.
1279
@param[in] val a floating-point to create a JSON number from
1281
@note RFC 7159 <http://www.rfc-editor.org/rfc/rfc7159.txt>, section 6
1282
disallows NaN values:
1283
> Numeric values that cannot be represented in the grammar below (such
1284
> as Infinity and NaN) are not permitted.
1285
In case the parameter @a val is not a number, a JSON null value is
1288
@complexity Constant.
1290
@liveexample{The example below shows the construction of several JSON
1291
floating-point number values from compatible
1292
types.,basic_json__CompatibleNumberFloatType}
1294
@sa @ref basic_json(const number_float_t) -- create a number value
1297
@since version 1.0.0
1299
template<typename CompatibleNumberFloatType, typename = typename
1301
std::is_constructible<number_float_t, CompatibleNumberFloatType>::value and
1302
std::is_floating_point<CompatibleNumberFloatType>::value>::type
1304
basic_json(const CompatibleNumberFloatType val) noexcept
1305
: basic_json(number_float_t(val))
1309
@brief create a container (array or object) from an initializer list
1311
Creates a JSON value of type array or object from the passed initializer
1312
list @a init. In case @a type_deduction is `true` (default), the type of
1313
the JSON value to be created is deducted from the initializer list @a init
1314
according to the following rules:
1316
1. If the list is empty, an empty JSON object value `{}` is created.
1317
2. If the list consists of pairs whose first element is a string, a JSON
1318
object value is created where the first elements of the pairs are treated
1319
as keys and the second elements are as values.
1320
3. In all other cases, an array is created.
1322
The rules aim to create the best fit between a C++ initializer list and
1323
JSON values. The ratioinale is as follows:
1325
1. The empty initializer list is written as `{}` which is exactly an empty
1327
2. C++ has now way of describing mapped types other than to list a list of
1328
pairs. As JSON requires that keys must be of type string, rule 2 is the
1329
weakest constraint one can pose on initializer lists to interpret them as
1331
3. In all other cases, the initializer list could not be interpreted as
1332
JSON object type, so interpreting it as JSON array type is safe.
1334
With the rules described above, the following JSON values cannot be
1335
expressed by an initializer list:
1337
- the empty array (`[]`): use @ref array(std::initializer_list<basic_json>)
1338
with an empty initializer list in this case
1339
- arrays whose elements satisfy rule 2: use @ref
1340
array(std::initializer_list<basic_json>) with the same initializer list
1343
@note When used without parentheses around an empty initializer list, @ref
1344
basic_json() is called instead of this function, yielding the JSON null
1347
@param[in] init initializer list with JSON values
1349
@param[in] type_deduction internal parameter; when set to `true`, the type
1350
of the JSON value is deducted from the initializer list @a init; when set
1351
to `false`, the type provided via @a manual_type is forced. This mode is
1352
used by the functions @ref array(std::initializer_list<basic_json>) and
1353
@ref object(std::initializer_list<basic_json>).
1355
@param[in] manual_type internal parameter; when @a type_deduction is set to
1356
`false`, the created JSON value will use the provided type (only @ref
1357
value_t::array and @ref value_t::object are valid); when @a type_deduction
1358
is set to `true`, this parameter has no effect
1360
@throw std::domain_error if @a type_deduction is `false`, @a manual_type is
1361
`value_t::object`, but @a init contains an element which is not a pair
1362
whose first element is a string; example: `"cannot create object from
1365
@complexity Linear in the size of the initializer list @a init.
1367
@liveexample{The example below shows how JSON values are created from
1368
initializer lists,basic_json__list_init_t}
1370
@sa @ref array(std::initializer_list<basic_json>) -- create a JSON array
1371
value from an initializer list
1372
@sa @ref object(std::initializer_list<basic_json>) -- create a JSON object
1373
value from an initializer list
1375
@since version 1.0.0
1377
basic_json(std::initializer_list<basic_json> init,
1378
bool type_deduction = true,
1379
value_t manual_type = value_t::array)
1381
// the initializer list could describe an object
1382
bool is_an_object = true;
1384
// check if each element is an array with two elements whose first
1385
// element is a string
1386
for (const auto& element : init)
1388
if (not element.is_array() or element.size() != 2
1389
or not element[0].is_string())
1391
// we found an element that makes it impossible to use the
1392
// initializer list as object
1393
is_an_object = false;
1398
// adjust type if type deduction is not wanted
1399
if (not type_deduction)
1401
// if array is wanted, do not create an object though possible
1402
if (manual_type == value_t::array)
1404
is_an_object = false;
1407
// if object is wanted but impossible, throw an exception
1408
if (manual_type == value_t::object and not is_an_object)
1410
throw std::domain_error("cannot create object from initializer list");
1416
// the initializer list is a list of pairs -> create object
1417
m_type = value_t::object;
1418
m_value = value_t::object;
1420
for (auto& element : init)
1422
m_value.object->emplace(std::move(*(element[0].m_value.string)), std::move(element[1]));
1427
// the initializer list describes an array -> create array
1428
m_type = value_t::array;
1429
m_value.array = create<array_t>(std::move(init));
1434
@brief explicitly create an array from an initializer list
1436
Creates a JSON array value from a given initializer list. That is, given a
1437
list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the
1438
initializer list is empty, the empty array `[]` is created.
1440
@note This function is only needed to express two edge cases that cannot be
1441
realized with the initializer list constructor (@ref
1442
basic_json(std::initializer_list<basic_json>, bool, value_t)). These cases
1444
1. creating an array whose elements are all pairs whose first element is a
1445
string -- in this case, the initializer list constructor would create an
1446
object, taking the first elements as keys
1447
2. creating an empty array -- passing the empty initializer list to the
1448
initializer list constructor yields an empty object
1450
@param[in] init initializer list with JSON values to create an array from
1453
@return JSON array value
1455
@complexity Linear in the size of @a init.
1457
@liveexample{The following code shows an example for the @ref array
1460
@sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) --
1461
create a JSON value from an initializer list
1462
@sa @ref object(std::initializer_list<basic_json>) -- create a JSON object
1463
value from an initializer list
1465
@since version 1.0.0
1467
static basic_json array(std::initializer_list<basic_json> init =
1468
std::initializer_list<basic_json>())
1470
return basic_json(init, false, value_t::array);
1474
@brief explicitly create an object from an initializer list
1476
Creates a JSON object value from a given initializer list. The initializer
1477
lists elements must be pairs, and their first elments must be strings. If
1478
the initializer list is empty, the empty object `{}` is created.
1480
@note This function is only added for symmetry reasons. In contrast to the
1481
related function @ref array(std::initializer_list<basic_json>), there are
1482
no cases which can only be expressed by this function. That is, any
1483
initializer list @a init can also be passed to the initializer list
1485
@ref basic_json(std::initializer_list<basic_json>, bool, value_t).
1487
@param[in] init initializer list to create an object from (optional)
1489
@return JSON object value
1491
@throw std::domain_error if @a init is not a pair whose first elements are
1493
@ref basic_json(std::initializer_list<basic_json>, bool, value_t)
1495
@complexity Linear in the size of @a init.
1497
@liveexample{The following code shows an example for the @ref object
1500
@sa @ref basic_json(std::initializer_list<basic_json>, bool, value_t) --
1501
create a JSON value from an initializer list
1502
@sa @ref array(std::initializer_list<basic_json>) -- create a JSON array
1503
value from an initializer list
1505
@since version 1.0.0
1507
static basic_json object(std::initializer_list<basic_json> init =
1508
std::initializer_list<basic_json>())
1510
return basic_json(init, false, value_t::object);
1514
@brief construct an array with count copies of given value
1516
Constructs a JSON array value by creating @a cnt copies of a passed
1517
value. In case @a cnt is `0`, an empty array is created. As postcondition,
1518
`std::distance(begin(),end()) == cnt` holds.
1520
@param[in] cnt the number of JSON copies of @a val to create
1521
@param[in] val the JSON value to copy
1523
@complexity Linear in @a cnt.
1525
@liveexample{The following code shows examples for the @ref
1526
basic_json(size_type\, const basic_json&)
1527
constructor.,basic_json__size_type_basic_json}
1529
@since version 1.0.0
1531
basic_json(size_type cnt, const basic_json& val)
1532
: m_type(value_t::array)
1534
m_value.array = create<array_t>(cnt, val);
1538
@brief construct a JSON container given an iterator range
1540
Constructs the JSON value with the contents of the range `[first, last)`.
1541
The semantics depends on the different types a JSON value can have:
1542
- In case of primitive types (number, boolean, or string), @a first must
1543
be `begin()` and @a last must be `end()`. In this case, the value is
1544
copied. Otherwise, std::out_of_range is thrown.
1545
- In case of structured types (array, object), the constructor behaves
1546
as similar versions for `std::vector`.
1547
- In case of a null type, std::domain_error is thrown.
1549
@tparam InputIT an input iterator type (@ref iterator or @ref
1552
@param[in] first begin of the range to copy from (included)
1553
@param[in] last end of the range to copy from (excluded)
1555
@throw std::domain_error if iterators are not compatible; that is, do not
1556
belong to the same JSON value; example: `"iterators are not compatible"`
1557
@throw std::out_of_range if iterators are for a primitive type (number,
1558
boolean, or string) where an out of range error can be detected easily;
1559
example: `"iterators out of range"`
1560
@throw std::bad_alloc if allocation for object, array, or string fails
1561
@throw std::domain_error if called with a null value; example: `"cannot use
1562
construct with iterators from null"`
1564
@complexity Linear in distance between @a first and @a last.
1566
@liveexample{The example below shows several ways to create JSON values by
1567
specifying a subrange with iterators.,basic_json__InputIt_InputIt}
1569
@since version 1.0.0
1571
template <class InputIT, typename
1573
std::is_same<InputIT, typename basic_json_t::iterator>::value or
1574
std::is_same<InputIT, typename basic_json_t::const_iterator>::value
1577
basic_json(InputIT first, InputIT last) : m_type(first.m_object->m_type)
1579
// make sure iterator fits the current value
1580
if (first.m_object != last.m_object)
1582
throw std::domain_error("iterators are not compatible");
1585
// check if iterator range is complete for primitive values
1588
case value_t::boolean:
1589
case value_t::number_float:
1590
case value_t::number_integer:
1591
case value_t::string:
1593
if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())
1595
throw std::out_of_range("iterators out of range");
1608
case value_t::number_integer:
1610
m_value.number_integer = first.m_object->m_value.number_integer;
1614
case value_t::number_float:
1616
m_value.number_float = first.m_object->m_value.number_float;
1620
case value_t::boolean:
1622
m_value.boolean = first.m_object->m_value.boolean;
1626
case value_t::string:
1628
m_value = *first.m_object->m_value.string;
1632
case value_t::object:
1634
m_value.object = create<object_t>(first.m_it.object_iterator, last.m_it.object_iterator);
1638
case value_t::array:
1640
m_value.array = create<array_t>(first.m_it.array_iterator, last.m_it.array_iterator);
1646
throw std::domain_error("cannot use construct with iterators from " + first.m_object->type_name());
1651
///////////////////////////////////////
1652
// other constructors and destructor //
1653
///////////////////////////////////////
1656
@brief copy constructor
1658
Creates a copy of a given JSON value.
1660
@param[in] other the JSON value to copy
1662
@complexity Linear in the size of @a other.
1664
@requirement This function satisfies the Container requirements:
1665
- The complexity is linear.
1666
- As postcondition, it holds: `other == basic_json(other)`.
1668
@throw std::bad_alloc if allocation for object, array, or string fails.
1670
@liveexample{The following code shows an example for the copy
1671
constructor.,basic_json__basic_json}
1673
@since version 1.0.0
1675
basic_json(const basic_json& other)
1676
: m_type(other.m_type)
1680
case value_t::object:
1682
m_value = *other.m_value.object;
1686
case value_t::array:
1688
m_value = *other.m_value.array;
1692
case value_t::string:
1694
m_value = *other.m_value.string;
1698
case value_t::boolean:
1700
m_value = other.m_value.boolean;
1704
case value_t::number_integer:
1706
m_value = other.m_value.number_integer;
1710
case value_t::number_float:
1712
m_value = other.m_value.number_float;
1724
@brief move constructor
1726
Move constructor. Constructs a JSON value with the contents of the given
1727
value @a other using move semantics. It "steals" the resources from @a
1728
other and leaves it as JSON null value.
1730
@param[in,out] other value to move to this object
1732
@post @a other is a JSON null value
1734
@complexity Constant.
1736
@liveexample{The code below shows the move constructor explicitly called
1737
via std::move.,basic_json__moveconstructor}
1739
@since version 1.0.0
1741
basic_json(basic_json&& other) noexcept
1742
: m_type(std::move(other.m_type)),
1743
m_value(std::move(other.m_value))
1745
// invalidate payload
1746
other.m_type = value_t::null;
1751
@brief copy assignment
1753
Copy assignment operator. Copies a JSON value via the "copy and swap"
1754
strategy: It is expressed in terms of the copy constructor, destructor, and
1755
the swap() member function.
1757
@param[in] other value to copy from
1761
@requirement This function satisfies the Container requirements:
1762
- The complexity is linear.
1764
@liveexample{The code below shows and example for the copy assignment. It
1765
creates a copy of value `a` which is then swapped with `b`. Finally\, the
1766
copy of `a` (which is the null value after the swap) is
1767
destroyed.,basic_json__copyassignment}
1769
@since version 1.0.0
1771
reference& operator=(basic_json other) noexcept (
1772
std::is_nothrow_move_constructible<value_t>::value and
1773
std::is_nothrow_move_assignable<value_t>::value and
1774
std::is_nothrow_move_constructible<json_value>::value and
1775
std::is_nothrow_move_assignable<json_value>::value
1779
swap(m_type, other.m_type);
1780
swap(m_value, other.m_value);
1787
Destroys the JSON value and frees all allocated memory.
1791
@requirement This function satisfies the Container requirements:
1792
- The complexity is linear.
1793
- All stored elements are destroyed and all memory is freed.
1795
@since version 1.0.0
1801
case value_t::object:
1803
AllocatorType<object_t> alloc;
1804
alloc.destroy(m_value.object);
1805
alloc.deallocate(m_value.object, 1);
1809
case value_t::array:
1811
AllocatorType<array_t> alloc;
1812
alloc.destroy(m_value.array);
1813
alloc.deallocate(m_value.array, 1);
1817
case value_t::string:
1819
AllocatorType<string_t> alloc;
1820
alloc.destroy(m_value.string);
1821
alloc.deallocate(m_value.string, 1);
1827
// all other types need no specific destructor
1836
///////////////////////
1837
// object inspection //
1838
///////////////////////
1840
/// @name object inspection
1844
@brief serialization
1846
Serialization function for JSON values. The function tries to mimick
1847
Python's @p json.dumps() function, and currently supports its @p indent
1850
@param[in] indent if indent is nonnegative, then array elements and object
1851
members will be pretty-printed with that indent level. An indent level of 0
1852
will only insert newlines. -1 (the default) selects the most compact
1855
@return string containing the serialization of the JSON value
1859
@liveexample{The following example shows the effect of different @a indent
1860
parameters to the result of the serializaion.,dump}
1862
@see https://docs.python.org/2/library/json.html#json.dump
1864
@since version 1.0.0
1866
string_t dump(const int indent = -1) const
1868
std::stringstream ss;
1872
dump(ss, true, static_cast<unsigned int>(indent));
1883
@brief return the type of the JSON value (explicit)
1885
Return the type of the JSON value as a value from the @ref value_t
1888
@return the type of the JSON value
1890
@complexity Constant.
1892
@liveexample{The following code exemplifies @ref type() for all JSON
1895
@since version 1.0.0
1897
value_t type() const noexcept
1903
@brief return whether type is primitive
1905
This function returns true iff the JSON type is primitive (string, number,
1908
@return `true` if type is primitive (string, number, boolean, or null),
1911
@complexity Constant.
1913
@liveexample{The following code exemplifies @ref is_primitive for all JSON
1914
types.,is_primitive}
1916
@since version 1.0.0
1918
bool is_primitive() const noexcept
1920
return is_null() or is_string() or is_boolean() or is_number();
1924
@brief return whether type is structured
1926
This function returns true iff the JSON type is structured (array or
1929
@return `true` if type is structured (array or object), `false` otherwise.
1931
@complexity Constant.
1933
@liveexample{The following code exemplifies @ref is_structured for all JSON
1934
types.,is_structured}
1936
@since version 1.0.0
1938
bool is_structured() const noexcept
1940
return is_array() or is_object();
1944
@brief return whether value is null
1946
This function returns true iff the JSON value is null.
1948
@return `true` if type is null, `false` otherwise.
1950
@complexity Constant.
1952
@liveexample{The following code exemplifies @ref is_null for all JSON
1955
@since version 1.0.0
1957
bool is_null() const noexcept
1959
return m_type == value_t::null;
1963
@brief return whether value is a boolean
1965
This function returns true iff the JSON value is a boolean.
1967
@return `true` if type is boolean, `false` otherwise.
1969
@complexity Constant.
1971
@liveexample{The following code exemplifies @ref is_boolean for all JSON
1974
@since version 1.0.0
1976
bool is_boolean() const noexcept
1978
return m_type == value_t::boolean;
1982
@brief return whether value is a number
1984
This function returns true iff the JSON value is a number. This includes
1985
both integer and floating-point values.
1987
@return `true` if type is number (regardless whether integer or
1988
floating-type), `false` otherwise.
1990
@complexity Constant.
1992
@liveexample{The following code exemplifies @ref is_number for all JSON
1995
@sa @ref is_number_integer() -- check if value is an integer number
1996
@sa @ref is_number_float() -- check if value is a floating-point number
1998
@since version 1.0.0
2000
bool is_number() const noexcept
2002
return is_number_integer() or is_number_float();
2006
@brief return whether value is an integer number
2008
This function returns true iff the JSON value is an integer number. This
2009
excludes floating-point values.
2011
@return `true` if type is an integer number, `false` otherwise.
2013
@complexity Constant.
2015
@liveexample{The following code exemplifies @ref is_number_integer for all
2016
JSON types.,is_number_integer}
2018
@sa @ref is_number() -- check if value is a number
2019
@sa @ref is_number_float() -- check if value is a floating-point number
2021
@since version 1.0.0
2023
bool is_number_integer() const noexcept
2025
return m_type == value_t::number_integer;
2029
@brief return whether value is a floating-point number
2031
This function returns true iff the JSON value is a floating-point number.
2032
This excludes integer values.
2034
@return `true` if type is a floating-point number, `false` otherwise.
2036
@complexity Constant.
2038
@liveexample{The following code exemplifies @ref is_number_float for all
2039
JSON types.,is_number_float}
2041
@sa @ref is_number() -- check if value is number
2042
@sa @ref is_number_integer() -- check if value is an integer number
2044
@since version 1.0.0
2046
bool is_number_float() const noexcept
2048
return m_type == value_t::number_float;
2052
@brief return whether value is an object
2054
This function returns true iff the JSON value is an object.
2056
@return `true` if type is object, `false` otherwise.
2058
@complexity Constant.
2060
@liveexample{The following code exemplifies @ref is_object for all JSON
2063
@since version 1.0.0
2065
bool is_object() const noexcept
2067
return m_type == value_t::object;
2071
@brief return whether value is an array
2073
This function returns true iff the JSON value is an array.
2075
@return `true` if type is array, `false` otherwise.
2077
@complexity Constant.
2079
@liveexample{The following code exemplifies @ref is_array for all JSON
2082
@since version 1.0.0
2084
bool is_array() const noexcept
2086
return m_type == value_t::array;
2090
@brief return whether value is a string
2092
This function returns true iff the JSON value is a string.
2094
@return `true` if type is string, `false` otherwise.
2096
@complexity Constant.
2098
@liveexample{The following code exemplifies @ref is_string for all JSON
2101
@since version 1.0.0
2103
bool is_string() const noexcept
2105
return m_type == value_t::string;
2109
@brief return whether value is discarded
2111
This function returns true iff the JSON value was discarded during parsing
2112
with a callback function (see @ref parser_callback_t).
2114
@note This function will always be `false` for JSON values after parsing.
2115
That is, discarded values can only occur during parsing, but will be
2116
removed when inside a structured value or replaced by null in other cases.
2118
@return `true` if type is discarded, `false` otherwise.
2120
@complexity Constant.
2122
@liveexample{The following code exemplifies @ref is_discarded for all JSON
2123
types.,is_discarded}
2125
@since version 1.0.0
2127
bool is_discarded() const noexcept
2129
return m_type == value_t::discarded;
2133
@brief return the type of the JSON value (implicit)
2135
Implicitly return the type of the JSON value as a value from the @ref
2136
value_t enumeration.
2138
@return the type of the JSON value
2140
@complexity Constant.
2142
@liveexample{The following code exemplifies the value_t operator for all
2143
JSON types.,operator__value_t}
2145
@since version 1.0.0
2147
operator value_t() const noexcept
2159
/// get an object (explicit)
2160
template <class T, typename
2162
std::is_convertible<typename object_t::key_type, typename T::key_type>::value and
2163
std::is_convertible<basic_json_t, typename T::mapped_type>::value
2165
T get_impl(T*) const
2169
return T(m_value.object->begin(), m_value.object->end());
2173
throw std::domain_error("type must be object, but is " + type_name());
2177
/// get an object (explicit)
2178
object_t get_impl(object_t*) const
2182
return *(m_value.object);
2186
throw std::domain_error("type must be object, but is " + type_name());
2190
/// get an array (explicit)
2191
template <class T, typename
2193
std::is_convertible<basic_json_t, typename T::value_type>::value and
2194
not std::is_same<basic_json_t, typename T::value_type>::value and
2195
not std::is_arithmetic<T>::value and
2196
not std::is_convertible<std::string, T>::value and
2197
not has_mapped_type<T>::value
2199
T get_impl(T*) const
2204
std::transform(m_value.array->begin(), m_value.array->end(),
2205
std::inserter(to_vector, to_vector.end()), [](basic_json i)
2207
return i.get<typename T::value_type>();
2213
throw std::domain_error("type must be array, but is " + type_name());
2217
/// get an array (explicit)
2218
template <class T, typename
2220
std::is_convertible<basic_json_t, T>::value and
2221
not std::is_same<basic_json_t, T>::value
2223
std::vector<T> get_impl(std::vector<T>*) const
2227
std::vector<T> to_vector;
2228
to_vector.reserve(m_value.array->size());
2229
std::transform(m_value.array->begin(), m_value.array->end(),
2230
std::inserter(to_vector, to_vector.end()), [](basic_json i)
2238
throw std::domain_error("type must be array, but is " + type_name());
2242
/// get an array (explicit)
2243
template <class T, typename
2245
std::is_same<basic_json, typename T::value_type>::value and
2246
not has_mapped_type<T>::value
2248
T get_impl(T*) const
2252
return T(m_value.array->begin(), m_value.array->end());
2256
throw std::domain_error("type must be array, but is " + type_name());
2260
/// get an array (explicit)
2261
array_t get_impl(array_t*) const
2265
return *(m_value.array);
2269
throw std::domain_error("type must be array, but is " + type_name());
2273
/// get a string (explicit)
2274
template <typename T, typename
2276
std::is_convertible<string_t, T>::value
2278
T get_impl(T*) const
2282
return *m_value.string;
2286
throw std::domain_error("type must be string, but is " + type_name());
2290
/// get a number (explicit)
2291
template<typename T, typename
2293
std::is_arithmetic<T>::value
2295
T get_impl(T*) const
2299
case value_t::number_integer:
2301
return static_cast<T>(m_value.number_integer);
2304
case value_t::number_float:
2306
return static_cast<T>(m_value.number_float);
2311
throw std::domain_error("type must be number, but is " + type_name());
2316
/// get a boolean (explicit)
2317
boolean_t get_impl(boolean_t*) const
2321
return m_value.boolean;
2325
throw std::domain_error("type must be boolean, but is " + type_name());
2329
/// get a pointer to the value (object)
2330
object_t* get_impl_ptr(object_t*) noexcept
2332
return is_object() ? m_value.object : nullptr;
2335
/// get a pointer to the value (object)
2336
const object_t* get_impl_ptr(const object_t*) const noexcept
2338
return is_object() ? m_value.object : nullptr;
2341
/// get a pointer to the value (array)
2342
array_t* get_impl_ptr(array_t*) noexcept
2344
return is_array() ? m_value.array : nullptr;
2347
/// get a pointer to the value (array)
2348
const array_t* get_impl_ptr(const array_t*) const noexcept
2350
return is_array() ? m_value.array : nullptr;
2353
/// get a pointer to the value (string)
2354
string_t* get_impl_ptr(string_t*) noexcept
2356
return is_string() ? m_value.string : nullptr;
2359
/// get a pointer to the value (string)
2360
const string_t* get_impl_ptr(const string_t*) const noexcept
2362
return is_string() ? m_value.string : nullptr;
2365
/// get a pointer to the value (boolean)
2366
boolean_t* get_impl_ptr(boolean_t*) noexcept
2368
return is_boolean() ? &m_value.boolean : nullptr;
2371
/// get a pointer to the value (boolean)
2372
const boolean_t* get_impl_ptr(const boolean_t*) const noexcept
2374
return is_boolean() ? &m_value.boolean : nullptr;
2377
/// get a pointer to the value (integer number)
2378
number_integer_t* get_impl_ptr(number_integer_t*) noexcept
2380
return is_number_integer() ? &m_value.number_integer : nullptr;
2383
/// get a pointer to the value (integer number)
2384
const number_integer_t* get_impl_ptr(const number_integer_t*) const noexcept
2386
return is_number_integer() ? &m_value.number_integer : nullptr;
2389
/// get a pointer to the value (floating-point number)
2390
number_float_t* get_impl_ptr(number_float_t*) noexcept
2392
return is_number_float() ? &m_value.number_float : nullptr;
2395
/// get a pointer to the value (floating-point number)
2396
const number_float_t* get_impl_ptr(const number_float_t*) const noexcept
2398
return is_number_float() ? &m_value.number_float : nullptr;
2403
/// @name value access
2407
@brief get a value (explicit)
2409
Explicit type conversion between the JSON value and a compatible value.
2411
@tparam ValueType non-pointer type compatible to the JSON value, for
2412
instance `int` for JSON integer numbers, `bool` for JSON booleans, or
2413
`std::vector` types for JSON arrays
2415
@return copy of the JSON value, converted to type @a ValueType
2417
@throw std::domain_error in case passed type @a ValueType is incompatible
2418
to JSON; example: `"type must be object, but is null"`
2420
@complexity Linear in the size of the JSON value.
2422
@liveexample{The example below shows serveral conversions from JSON values
2423
to other types. There a few things to note: (1) Floating-point numbers can
2424
be converted to integers\, (2) A JSON array can be converted to a standard
2425
`std::vector<short>`\, (3) A JSON object can be converted to C++
2426
assiciative containers such as `std::unordered_map<std::string\,
2427
json>`.,get__ValueType_const}
2430
The idea of using a casted null pointer to choose the correct
2431
implementation is from <http://stackoverflow.com/a/8315197/266378>.
2434
@sa @ref operator ValueType() const for implicit conversion
2435
@sa @ref get() for pointer-member access
2437
@since version 1.0.0
2439
template<typename ValueType, typename
2441
not std::is_pointer<ValueType>::value
2443
ValueType get() const
2445
return get_impl(static_cast<ValueType*>(nullptr));
2449
@brief get a pointer value (explicit)
2451
Explicit pointer access to the internally stored JSON value. No copies are
2454
@warning The pointer becomes invalid if the underlying JSON object changes.
2456
@tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
2457
object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or @ref
2460
@return pointer to the internally stored JSON value if the requested
2461
pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
2463
@complexity Constant.
2465
@liveexample{The example below shows how pointers to internal values of a
2466
JSON value can be requested. Note that no type conversions are made and a
2467
`nullptr` is returned if the value and the requested pointer type does not
2468
match.,get__PointerType}
2470
@sa @ref get_ptr() for explicit pointer-member access
2472
@since version 1.0.0
2474
template<typename PointerType, typename
2476
std::is_pointer<PointerType>::value
2478
PointerType get() noexcept
2480
// delegate the call to get_ptr
2481
return get_ptr<PointerType>();
2485
@brief get a pointer value (explicit)
2488
template<typename PointerType, typename
2490
std::is_pointer<PointerType>::value
2492
const PointerType get() const noexcept
2494
// delegate the call to get_ptr
2495
return get_ptr<PointerType>();
2499
@brief get a pointer value (implicit)
2501
Implict pointer access to the internally stored JSON value. No copies are
2504
@warning Writing data to the pointee of the result yields an undefined
2507
@tparam PointerType pointer type; must be a pointer to @ref array_t, @ref
2508
object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or @ref
2511
@return pointer to the internally stored JSON value if the requested
2512
pointer type @a PointerType fits to the JSON value; `nullptr` otherwise
2514
@complexity Constant.
2516
@liveexample{The example below shows how pointers to internal values of a
2517
JSON value can be requested. Note that no type conversions are made and a
2518
`nullptr` is returned if the value and the requested pointer type does not
2521
@since version 1.0.0
2523
template<typename PointerType, typename
2525
std::is_pointer<PointerType>::value
2527
PointerType get_ptr() noexcept
2529
// delegate the call to get_impl_ptr<>()
2530
return get_impl_ptr(static_cast<PointerType>(nullptr));
2534
@brief get a pointer value (implicit)
2537
template<typename PointerType, typename
2539
std::is_pointer<PointerType>::value
2540
and std::is_const<typename std::remove_pointer<PointerType>::type>::value
2542
const PointerType get_ptr() const noexcept
2544
// delegate the call to get_impl_ptr<>() const
2545
return get_impl_ptr(static_cast<const PointerType>(nullptr));
2549
@brief get a value (implicit)
2551
Implict type conversion between the JSON value and a compatible value. The
2552
call is realized by calling @ref get() const.
2554
@tparam ValueType non-pointer type compatible to the JSON value, for
2555
instance `int` for JSON integer numbers, `bool` for JSON booleans, or
2556
`std::vector` types for JSON arrays. The character type of @ref string_t
2557
as well as an initializer list of this type is excluded to avoid
2558
ambiguities as these types implicitly convert to `std::string`.
2560
@return copy of the JSON value, converted to type @a ValueType
2562
@throw std::domain_error in case passed type @a ValueType is incompatible
2563
to JSON, thrown by @ref get() const
2565
@complexity Linear in the size of the JSON value.
2567
@liveexample{The example below shows serveral conversions from JSON values
2568
to other types. There a few things to note: (1) Floating-point numbers can
2569
be converted to integers\, (2) A JSON array can be converted to a standard
2570
`std::vector<short>`\, (3) A JSON object can be converted to C++
2571
assiciative containers such as `std::unordered_map<std::string\,
2572
json>`.,operator__ValueType}
2574
@since version 1.0.0
2576
template<typename ValueType, typename
2578
not std::is_pointer<ValueType>::value
2579
and not std::is_same<ValueType, typename string_t::value_type>::value
2580
and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value
2582
operator ValueType() const
2584
// delegate the call to get<>() const
2585
return get<ValueType>();
2591
////////////////////
2592
// element access //
2593
////////////////////
2595
/// @name element access
2599
@brief access specified array element with bounds checking
2601
Returns a reference to the element at specified location @a idx, with
2604
@param[in] idx index of the element to access
2606
@return reference to the element at index @a idx
2608
@throw std::domain_error if the JSON value is not an array; example:
2609
`"cannot use at() with string"`
2610
@throw std::out_of_range if the index @a idx is out of range of the array;
2611
that is, `idx >= size()`; example: `"array index 7 is out of range"`
2613
@complexity Constant.
2615
@liveexample{The example below shows how array elements can be read and
2616
written using at.,at__size_type}
2618
@since version 1.0.0
2620
reference at(size_type idx)
2622
// at only works for arrays
2627
return m_value.array->at(idx);
2629
catch (std::out_of_range& e)
2631
// create better exception explanation
2632
throw std::out_of_range("array index " + std::to_string(idx) + " is out of range");
2637
throw std::domain_error("cannot use at() with " + type_name());
2642
@brief access specified array element with bounds checking
2644
Returns a const reference to the element at specified location @a idx, with
2647
@param[in] idx index of the element to access
2649
@return const reference to the element at index @a idx
2651
@throw std::domain_error if the JSON value is not an array; example:
2652
`"cannot use at() with string"`
2653
@throw std::out_of_range if the index @a idx is out of range of the array;
2654
that is, `idx >= size()`; example: `"array index 7 is out of range"`
2656
@complexity Constant.
2658
@liveexample{The example below shows how array elements can be read using
2659
at.,at__size_type_const}
2661
@since version 1.0.0
2663
const_reference at(size_type idx) const
2665
// at only works for arrays
2670
return m_value.array->at(idx);
2672
catch (std::out_of_range& e)
2674
// create better exception explanation
2675
throw std::out_of_range("array index " + std::to_string(idx) + " is out of range");
2680
throw std::domain_error("cannot use at() with " + type_name());
2685
@brief access specified object element with bounds checking
2687
Returns a reference to the element at with specified key @a key, with
2690
@param[in] key key of the element to access
2692
@return reference to the element at key @a key
2694
@throw std::domain_error if the JSON value is not an object; example:
2695
`"cannot use at() with boolean"`
2696
@throw std::out_of_range if the key @a key is is not stored in the object;
2697
that is, `find(key) == end()`; example: `"key "the fast" not found"`
2699
@complexity Logarithmic in the size of the container.
2701
@liveexample{The example below shows how object elements can be read and
2702
written using at.,at__object_t_key_type}
2704
@sa @ref operator[](const typename object_t::key_type&) for unchecked
2706
@sa @ref value() for access by value with a default value
2708
@since version 1.0.0
2710
reference at(const typename object_t::key_type& key)
2712
// at only works for objects
2717
return m_value.object->at(key);
2719
catch (std::out_of_range& e)
2721
// create better exception explanation
2722
throw std::out_of_range("key '" + key + "' not found");
2727
throw std::domain_error("cannot use at() with " + type_name());
2732
@brief access specified object element with bounds checking
2734
Returns a const reference to the element at with specified key @a key, with
2737
@param[in] key key of the element to access
2739
@return const reference to the element at key @a key
2741
@throw std::domain_error if the JSON value is not an object; example:
2742
`"cannot use at() with boolean"`
2743
@throw std::out_of_range if the key @a key is is not stored in the object;
2744
that is, `find(key) == end()`; example: `"key "the fast" not found"`
2746
@complexity Logarithmic in the size of the container.
2748
@liveexample{The example below shows how object elements can be read using
2749
at.,at__object_t_key_type_const}
2751
@sa @ref operator[](const typename object_t::key_type&) for unchecked
2753
@sa @ref value() for access by value with a default value
2755
@since version 1.0.0
2757
const_reference at(const typename object_t::key_type& key) const
2759
// at only works for objects
2764
return m_value.object->at(key);
2766
catch (std::out_of_range& e)
2768
// create better exception explanation
2769
throw std::out_of_range("key '" + key + "' not found");
2774
throw std::domain_error("cannot use at() with " + type_name());
2779
@brief access specified array element
2781
Returns a reference to the element at specified location @a idx.
2783
@note If @a idx is beyond the range of the array (i.e., `idx >= size()`),
2784
then the array is silently filled up with `null` values to make `idx` a
2785
valid reference to the last stored element.
2787
@param[in] idx index of the element to access
2789
@return reference to the element at index @a idx
2791
@throw std::domain_error if JSON is not an array or null; example: `"cannot
2792
use operator[] with null"`
2794
@complexity Constant if @a idx is in the range of the array. Otherwise
2795
linear in `idx - size()`.
2797
@liveexample{The example below shows how array elements can be read and
2798
written using [] operator. Note the addition of `null`
2799
values.,operatorarray__size_type}
2801
@since version 1.0.0
2803
reference operator[](size_type idx)
2805
// implicitly convert null to object
2808
m_type = value_t::array;
2809
m_value.array = create<array_t>();
2812
// [] only works for arrays
2815
for (size_t i = m_value.array->size(); i <= idx; ++i)
2817
m_value.array->push_back(basic_json());
2820
return m_value.array->operator[](idx);
2824
throw std::domain_error("cannot use operator[] with " + type_name());
2829
@brief access specified array element
2831
Returns a const reference to the element at specified location @a idx.
2833
@param[in] idx index of the element to access
2835
@return const reference to the element at index @a idx
2837
@throw std::domain_error if JSON is not an array; example: `"cannot use
2838
operator[] with null"`
2840
@complexity Constant.
2842
@liveexample{The example below shows how array elements can be read using
2843
the [] operator.,operatorarray__size_type_const}
2845
@since version 1.0.0
2847
const_reference operator[](size_type idx) const
2849
// at only works for arrays
2852
return m_value.array->operator[](idx);
2856
throw std::domain_error("cannot use operator[] with " + type_name());
2861
@brief access specified object element
2863
Returns a reference to the element at with specified key @a key.
2865
@note If @a key is not found in the object, then it is silently added to
2866
the object and filled with a `null` value to make `key` a valid reference.
2867
In case the value was `null` before, it is converted to an object.
2869
@param[in] key key of the element to access
2871
@return reference to the element at key @a key
2873
@throw std::domain_error if JSON is not an object or null; example:
2874
`"cannot use operator[] with null"`
2876
@complexity Logarithmic in the size of the container.
2878
@liveexample{The example below shows how object elements can be read and
2879
written using the [] operator.,operatorarray__key_type}
2881
@sa @ref at(const typename object_t::key_type&) for access by reference
2883
@sa @ref value() for access by value with a default value
2885
@since version 1.0.0
2887
reference operator[](const typename object_t::key_type& key)
2889
// implicitly convert null to object
2892
m_type = value_t::object;
2893
m_value.object = create<object_t>();
2896
// [] only works for objects
2899
return m_value.object->operator[](key);
2903
throw std::domain_error("cannot use operator[] with " + type_name());
2908
@brief read-only access specified object element
2910
Returns a const reference to the element at with specified key @a key. No
2911
bounds checking is performed.
2913
@warning If the element with key @a key does not exist, the behavior is
2916
@param[in] key key of the element to access
2918
@return const reference to the element at key @a key
2920
@throw std::domain_error if JSON is not an object; example: `"cannot use
2921
operator[] with null"`
2923
@complexity Logarithmic in the size of the container.
2925
@liveexample{The example below shows how object elements can be read using
2926
the [] operator.,operatorarray__key_type_const}
2928
@sa @ref at(const typename object_t::key_type&) for access by reference
2930
@sa @ref value() for access by value with a default value
2932
@since version 1.0.0
2934
const_reference operator[](const typename object_t::key_type& key) const
2936
// [] only works for objects
2939
return m_value.object->find(key)->second;
2943
throw std::domain_error("cannot use operator[] with " + type_name());
2948
@brief access specified object element
2950
Returns a reference to the element at with specified key @a key.
2952
@note If @a key is not found in the object, then it is silently added to
2953
the object and filled with a `null` value to make `key` a valid reference.
2954
In case the value was `null` before, it is converted to an object.
2956
@note This function is required for compatibility reasons with Clang.
2958
@param[in] key key of the element to access
2960
@return reference to the element at key @a key
2962
@throw std::domain_error if JSON is not an object or null; example:
2963
`"cannot use operator[] with null"`
2965
@complexity Logarithmic in the size of the container.
2967
@liveexample{The example below shows how object elements can be read and
2968
written using the [] operator.,operatorarray__key_type}
2970
@sa @ref at(const typename object_t::key_type&) for access by reference
2972
@sa @ref value() for access by value with a default value
2974
@since version 1.0.0
2976
template<typename T, std::size_t n>
2977
reference operator[](const T (&key)[n])
2979
// implicitly convert null to object
2982
m_type = value_t::object;
2983
m_value = value_t::object;
2986
// at only works for objects
2989
return m_value.object->operator[](key);
2993
throw std::domain_error("cannot use operator[] with " + type_name());
2998
@brief read-only access specified object element
3000
Returns a const reference to the element at with specified key @a key. No
3001
bounds checking is performed.
3003
@warning If the element with key @a key does not exist, the behavior is
3006
@note This function is required for compatibility reasons with Clang.
3008
@param[in] key key of the element to access
3010
@return const reference to the element at key @a key
3012
@throw std::domain_error if JSON is not an object; example: `"cannot use
3013
operator[] with null"`
3015
@complexity Logarithmic in the size of the container.
3017
@liveexample{The example below shows how object elements can be read using
3018
the [] operator.,operatorarray__key_type_const}
3020
@sa @ref at(const typename object_t::key_type&) for access by reference
3022
@sa @ref value() for access by value with a default value
3024
@since version 1.0.0
3026
template<typename T, std::size_t n>
3027
const_reference operator[](const T (&key)[n]) const
3029
// at only works for objects
3032
return m_value.object->find(key)->second;
3036
throw std::domain_error("cannot use operator[] with " + type_name());
3041
@brief access specified object element with default value
3043
Returns either a copy of an object's element at the specified key @a key or
3044
a given default value if no element with key @a key exists.
3046
The function is basically equivalent to executing
3050
} catch(std::out_of_range) {
3051
return default_value;
3055
@note Unlike @ref at(const typename object_t::key_type&), this function
3056
does not throw if the given key @a key was not found.
3058
@note Unlike @ref operator[](const typename object_t::key_type& key), this
3059
function does not implicitly add an element to the position defined by @a
3060
key. This function is furthermore also applicable to const objects.
3062
@param[in] key key of the element to access
3063
@param[in] default_value the value to return if @a key is not found
3065
@tparam ValueType type compatible to JSON values, for instance `int` for
3066
JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for
3067
JSON arrays. Note the type of the expected value at @a key and the default
3068
value @a default_value must be compatible.
3070
@return copy of the element at key @a key or @a default_value if @a key
3073
@throw std::domain_error if JSON is not an object; example: `"cannot use
3076
@complexity Logarithmic in the size of the container.
3078
@liveexample{The example below shows how object elements can be queried
3079
with a default value.,basic_json__value}
3081
@sa @ref at(const typename object_t::key_type&) for access by reference
3083
@sa @ref operator[](const typename object_t::key_type&) for unchecked
3086
@since version 1.0.0
3088
template <class ValueType, typename
3090
std::is_convertible<basic_json_t, ValueType>::value
3092
ValueType value(const typename object_t::key_type& key, ValueType default_value) const
3094
// at only works for objects
3097
// if key is found, return value and given default value otherwise
3098
const auto it = find(key);
3105
return default_value;
3110
throw std::domain_error("cannot use value() with " + type_name());
3115
@brief overload for a default value of type const char*
3116
@copydoc basic_json::value()
3118
string_t value(const typename object_t::key_type& key, const char* default_value) const
3120
return value(key, string_t(default_value));
3124
@brief access the first element
3126
Returns a reference to the first element in the container. For a JSON
3127
container `c`, the expression `c.front()` is equivalent to `*c.begin()`.
3129
@return In case of a structured type (array or object), a reference to the
3130
first element is returned. In cast of number, string, or boolean values, a
3131
reference to the value is returned.
3133
@complexity Constant.
3135
@note Calling `front` on an empty container is undefined.
3137
@throw std::out_of_range when called on null value
3139
@liveexample{The following code shows an example for @ref front.,front}
3141
@since version 1.0.0
3149
@copydoc basic_json::front()
3151
const_reference front() const
3157
@brief access the last element
3159
Returns a reference to the last element in the container. For a JSON
3160
container `c`, the expression `c.back()` is equivalent to `{ auto tmp =
3161
c.end(); --tmp; return *tmp; }`.
3163
@return In case of a structured type (array or object), a reference to the
3164
last element is returned. In cast of number, string, or boolean values, a
3165
reference to the value is returned.
3167
@complexity Constant.
3169
@note Calling `back` on an empty container is undefined.
3171
@throw std::out_of_range when called on null value.
3173
@liveexample{The following code shows an example for @ref back.,back}
3175
@since version 1.0.0
3185
@copydoc basic_json::back()
3187
const_reference back() const
3195
@brief remove element given an iterator
3197
Removes the element specified by iterator @a pos. Invalidates iterators and
3198
references at or after the point of the erase, including the end()
3199
iterator. The iterator @a pos must be valid and dereferenceable. Thus the
3200
end() iterator (which is valid, but is not dereferencable) cannot be used
3201
as a value for @a pos.
3203
If called on a primitive type other than null, the resulting JSON value
3206
@param[in] pos iterator to the element to remove
3207
@return Iterator following the last removed element. If the iterator @a pos
3208
refers to the last element, the end() iterator is returned.
3210
@tparam InteratorType an @ref iterator or @ref const_iterator
3212
@throw std::domain_error if called on a `null` value; example: `"cannot use
3214
@throw std::domain_error if called on an iterator which does not belong to
3215
the current JSON value; example: `"iterator does not fit current value"`
3216
@throw std::out_of_range if called on a primitive type with invalid
3217
iterator (i.e., any iterator which is not end()); example: `"iterator out
3220
@complexity The complexity depends on the type:
3221
- objects: amortized constant
3222
- arrays: linear in distance between pos and the end of the container
3223
- strings: linear in the length of the string
3224
- other types: constant
3226
@liveexample{The example shows the result of erase for different JSON
3227
types.,erase__IteratorType}
3229
@sa @ref erase(InteratorType, InteratorType) -- removes the elements in the
3231
@sa @ref erase(const typename object_t::key_type&) -- remvoes the element
3232
from an object at the given key
3233
@sa @ref erase(const size_type) -- removes the element from an array at the
3236
@since version 1.0.0
3238
template <class InteratorType, typename
3240
std::is_same<InteratorType, typename basic_json_t::iterator>::value or
3241
std::is_same<InteratorType, typename basic_json_t::const_iterator>::value
3244
InteratorType erase(InteratorType pos)
3246
// make sure iterator fits the current value
3247
if (this != pos.m_object)
3249
throw std::domain_error("iterator does not fit current value");
3252
InteratorType result = end();
3256
case value_t::boolean:
3257
case value_t::number_float:
3258
case value_t::number_integer:
3259
case value_t::string:
3261
if (not pos.m_it.primitive_iterator.is_begin())
3263
throw std::out_of_range("iterator out of range");
3268
delete m_value.string;
3269
m_value.string = nullptr;
3272
m_type = value_t::null;
3276
case value_t::object:
3278
result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator);
3282
case value_t::array:
3284
result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator);
3290
throw std::domain_error("cannot use erase() with " + type_name());
3298
@brief remove elements given an iterator range
3300
Removes the element specified by the range `[first; last)`. Invalidates
3301
iterators and references at or after the point of the erase, including the
3302
end() iterator. The iterator @a first does not need to be dereferenceable
3303
if `first == last`: erasing an empty range is a no-op.
3305
If called on a primitive type other than null, the resulting JSON value
3308
@param[in] first iterator to the beginning of the range to remove
3309
@param[in] last iterator past the end of the range to remove
3310
@return Iterator following the last removed element. If the iterator @a
3311
second refers to the last element, the end() iterator is returned.
3313
@tparam InteratorType an @ref iterator or @ref const_iterator
3315
@throw std::domain_error if called on a `null` value; example: `"cannot use
3317
@throw std::domain_error if called on iterators which does not belong to
3318
the current JSON value; example: `"iterators do not fit current value"`
3319
@throw std::out_of_range if called on a primitive type with invalid
3320
iterators (i.e., if `first != begin()` and `last != end()`); example:
3321
`"iterators out of range"`
3323
@complexity The complexity depends on the type:
3324
- objects: `log(size()) + std::distance(first, last)`
3325
- arrays: linear in the distance between @a first and @a last, plus linear
3326
in the distance between @a last and end of the container
3327
- strings: linear in the length of the string
3328
- other types: constant
3330
@liveexample{The example shows the result of erase for different JSON
3331
types.,erase__IteratorType_IteratorType}
3333
@sa @ref erase(InteratorType) -- removes the element at a given position
3334
@sa @ref erase(const typename object_t::key_type&) -- remvoes the element
3335
from an object at the given key
3336
@sa @ref erase(const size_type) -- removes the element from an array at the
3339
@since version 1.0.0
3341
template <class InteratorType, typename
3343
std::is_same<InteratorType, typename basic_json_t::iterator>::value or
3344
std::is_same<InteratorType, typename basic_json_t::const_iterator>::value
3347
InteratorType erase(InteratorType first, InteratorType last)
3349
// make sure iterator fits the current value
3350
if (this != first.m_object or this != last.m_object)
3352
throw std::domain_error("iterators do not fit current value");
3355
InteratorType result = end();
3359
case value_t::boolean:
3360
case value_t::number_float:
3361
case value_t::number_integer:
3362
case value_t::string:
3364
if (not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())
3366
throw std::out_of_range("iterators out of range");
3371
delete m_value.string;
3372
m_value.string = nullptr;
3375
m_type = value_t::null;
3379
case value_t::object:
3381
result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator,
3382
last.m_it.object_iterator);
3386
case value_t::array:
3388
result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator,
3389
last.m_it.array_iterator);
3395
throw std::domain_error("cannot use erase() with " + type_name());
3403
@brief remove element from a JSON object given a key
3405
Removes elements from a JSON object with the key value @a key.
3407
@param[in] key value of the elements to remove
3409
@return Number of elements removed. If ObjectType is the default `std::map`
3410
type, the return value will always be `0` (@a key was not found) or `1` (@a
3413
@throw std::domain_error when called on a type other than JSON object;
3414
example: `"cannot use erase() with null"`
3416
@complexity `log(size()) + count(key)`
3418
@liveexample{The example shows the effect of erase.,erase__key_type}
3420
@sa @ref erase(InteratorType) -- removes the element at a given position
3421
@sa @ref erase(InteratorType, InteratorType) -- removes the elements in the
3423
@sa @ref erase(const size_type) -- removes the element from an array at the
3426
@since version 1.0.0
3428
size_type erase(const typename object_t::key_type& key)
3430
// this erase only works for objects
3433
return m_value.object->erase(key);
3437
throw std::domain_error("cannot use erase() with " + type_name());
3442
@brief remove element from a JSON array given an index
3444
Removes element from a JSON array at the index @a idx.
3446
@param[in] idx index of the element to remove
3448
@throw std::domain_error when called on a type other than JSON array;
3449
example: `"cannot use erase() with null"`
3450
@throw std::out_of_range when `idx >= size()`; example: `"index out of
3453
@complexity Linear in distance between @a idx and the end of the container.
3455
@liveexample{The example shows the effect of erase.,erase__size_type}
3457
@sa @ref erase(InteratorType) -- removes the element at a given position
3458
@sa @ref erase(InteratorType, InteratorType) -- removes the elements in the
3460
@sa @ref erase(const typename object_t::key_type&) -- remvoes the element
3461
from an object at the given key
3463
@since version 1.0.0
3465
void erase(const size_type idx)
3467
// this erase only works for arrays
3472
throw std::out_of_range("index out of range");
3475
m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx));
3479
throw std::domain_error("cannot use erase() with " + type_name());
3484
@brief find an element in a JSON object
3486
Finds an element in a JSON object with key equivalent to @a key. If the
3487
element is not found or the JSON value is not an object, end() is returned.
3489
@param[in] key key value of the element to search for
3491
@return Iterator to an element with key equivalent to @a key. If no such
3492
element is found, past-the-end (see end()) iterator is returned.
3494
@complexity Logarithmic in the size of the JSON object.
3496
@liveexample{The example shows how find is used.,find__key_type}
3498
@since version 1.0.0
3500
iterator find(typename object_t::key_type key)
3502
auto result = end();
3506
result.m_it.object_iterator = m_value.object->find(key);
3513
@brief find an element in a JSON object
3514
@copydoc find(typename object_t::key_type)
3516
const_iterator find(typename object_t::key_type key) const
3518
auto result = cend();
3522
result.m_it.object_iterator = m_value.object->find(key);
3529
@brief returns the number of occurrences of a key in a JSON object
3531
Returns the number of elements with key @a key. If ObjectType is the
3532
default `std::map` type, the return value will always be `0` (@a key was
3533
not found) or `1` (@a key was found).
3535
@param[in] key key value of the element to count
3537
@return Number of elements with key @a key. If the JSON value is not an
3538
object, the return value will be `0`.
3540
@complexity Logarithmic in the size of the JSON object.
3542
@liveexample{The example shows how count is used.,count}
3544
@since version 1.0.0
3546
size_type count(typename object_t::key_type key) const
3548
// return 0 for all nonobject types
3549
return is_object() ? m_value.object->count(key) : 0;
3563
@brief returns an iterator to the first element
3565
Returns an iterator to the first element.
3567
@image html range-begin-end.svg "Illustration from cppreference.com"
3569
@return iterator to the first element
3571
@complexity Constant.
3573
@requirement This function satisfies the Container requirements:
3574
- The complexity is constant.
3576
@liveexample{The following code shows an example for @ref begin.,begin}
3578
@since version 1.0.0
3582
iterator result(this);
3588
@copydoc basic_json::cbegin()
3590
const_iterator begin() const
3596
@brief returns a const iterator to the first element
3598
Returns a const iterator to the first element.
3600
@image html range-begin-end.svg "Illustration from cppreference.com"
3602
@return const iterator to the first element
3604
@complexity Constant.
3606
@requirement This function satisfies the Container requirements:
3607
- The complexity is constant.
3608
- Has the semantics of `const_cast<const basic_json&>(*this).begin()`.
3610
@liveexample{The following code shows an example for @ref cbegin.,cbegin}
3612
@since version 1.0.0
3614
const_iterator cbegin() const
3616
const_iterator result(this);
3622
@brief returns an iterator to one past the last element
3624
Returns an iterator to one past the last element.
3626
@image html range-begin-end.svg "Illustration from cppreference.com"
3628
@return iterator one past the last element
3630
@complexity Constant.
3632
@requirement This function satisfies the Container requirements:
3633
- The complexity is constant.
3635
@liveexample{The following code shows an example for @ref end.,end}
3637
@since version 1.0.0
3641
iterator result(this);
3647
@copydoc basic_json::cend()
3649
const_iterator end() const
3655
@brief returns a const iterator to one past the last element
3657
Returns a const iterator to one past the last element.
3659
@image html range-begin-end.svg "Illustration from cppreference.com"
3661
@return const iterator one past the last element
3663
@complexity Constant.
3665
@requirement This function satisfies the Container requirements:
3666
- The complexity is constant.
3667
- Has the semantics of `const_cast<const basic_json&>(*this).end()`.
3669
@liveexample{The following code shows an example for @ref cend.,cend}
3671
@since version 1.0.0
3673
const_iterator cend() const
3675
const_iterator result(this);
3681
@brief returns an iterator to the reverse-beginning
3683
Returns an iterator to the reverse-beginning; that is, the last element.
3685
@image html range-rbegin-rend.svg "Illustration from cppreference.com"
3687
@complexity Constant.
3689
@requirement This function satisfies the ReversibleContainer requirements:
3690
- The complexity is constant.
3691
- Has the semantics of `reverse_iterator(end())`.
3693
@liveexample{The following code shows an example for @ref rbegin.,rbegin}
3695
@since version 1.0.0
3697
reverse_iterator rbegin()
3699
return reverse_iterator(end());
3703
@copydoc basic_json::crbegin()
3705
const_reverse_iterator rbegin() const
3711
@brief returns an iterator to the reverse-end
3713
Returns an iterator to the reverse-end; that is, one before the first
3716
@image html range-rbegin-rend.svg "Illustration from cppreference.com"
3718
@complexity Constant.
3720
@requirement This function satisfies the ReversibleContainer requirements:
3721
- The complexity is constant.
3722
- Has the semantics of `reverse_iterator(begin())`.
3724
@liveexample{The following code shows an example for @ref rend.,rend}
3726
@since version 1.0.0
3728
reverse_iterator rend()
3730
return reverse_iterator(begin());
3734
@copydoc basic_json::crend()
3736
const_reverse_iterator rend() const
3742
@brief returns a const reverse iterator to the last element
3744
Returns a const iterator to the reverse-beginning; that is, the last
3747
@image html range-rbegin-rend.svg "Illustration from cppreference.com"
3749
@complexity Constant.
3751
@requirement This function satisfies the ReversibleContainer requirements:
3752
- The complexity is constant.
3753
- Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`.
3755
@liveexample{The following code shows an example for @ref crbegin.,crbegin}
3757
@since version 1.0.0
3759
const_reverse_iterator crbegin() const
3761
return const_reverse_iterator(cend());
3765
@brief returns a const reverse iterator to one before the first
3767
Returns a const reverse iterator to the reverse-end; that is, one before
3770
@image html range-rbegin-rend.svg "Illustration from cppreference.com"
3772
@complexity Constant.
3774
@requirement This function satisfies the ReversibleContainer requirements:
3775
- The complexity is constant.
3776
- Has the semantics of `const_cast<const basic_json&>(*this).rend()`.
3778
@liveexample{The following code shows an example for @ref crend.,crend}
3780
@since version 1.0.0
3782
const_reverse_iterator crend() const
3784
return const_reverse_iterator(cbegin());
3788
// forward declaration
3789
template<typename IteratorType> class iteration_proxy;
3793
@brief wrapper to access iterator member functions in range-based for
3795
This functuion allows to access @ref iterator::key() and @ref
3796
iterator::value() during range-based for loops. In these loops, a reference
3797
to the JSON values is returned, so there is no access to the underlying
3800
@note The name of this function is not yet final and may change in the
3803
static iteration_proxy<iterator> iterator_wrapper(reference cont)
3805
return iteration_proxy<iterator>(cont);
3809
@copydoc iterator_wrapper(reference)
3811
static iteration_proxy<const_iterator> iterator_wrapper(const_reference cont)
3813
return iteration_proxy<const_iterator>(cont);
3827
@brief checks whether the container is empty
3829
Checks if a JSON value has no elements.
3831
@return The return value depends on the different types and is
3833
Value type | return value
3834
----------- | -------------
3839
object | result of function object_t::empty()
3840
array | result of function array_t::empty()
3842
@complexity Constant, as long as @ref array_t and @ref object_t satisfy the
3843
Container concept; that is, their empty() functions have constant
3846
@requirement This function satisfies the Container requirements:
3847
- The complexity is constant.
3848
- Has the semantics of `begin() == end()`.
3850
@liveexample{The following code uses @ref empty to check if a @ref json
3851
object contains any elements.,empty}
3853
@since version 1.0.0
3855
bool empty() const noexcept
3861
// null values are empty
3865
case value_t::array:
3867
return m_value.array->empty();
3870
case value_t::object:
3872
return m_value.object->empty();
3877
// all other types are nonempty
3884
@brief returns the number of elements
3886
Returns the number of elements in a JSON value.
3888
@return The return value depends on the different types and is
3890
Value type | return value
3891
----------- | -------------
3896
object | result of function object_t::size()
3897
array | result of function array_t::size()
3899
@complexity Constant, as long as @ref array_t and @ref object_t satisfy the
3900
Container concept; that is, their size() functions have constant complexity.
3902
@requirement This function satisfies the Container requirements:
3903
- The complexity is constant.
3904
- Has the semantics of `std::distance(begin(), end())`.
3906
@liveexample{The following code calls @ref size on the different value
3909
@since version 1.0.0
3911
size_type size() const noexcept
3917
// null values are empty
3921
case value_t::array:
3923
return m_value.array->size();
3926
case value_t::object:
3928
return m_value.object->size();
3933
// all other types have size 1
3940
@brief returns the maximum possible number of elements
3942
Returns the maximum number of elements a JSON value is able to hold due to
3943
system or library implementation limitations, i.e. `std::distance(begin(),
3944
end())` for the JSON value.
3946
@return The return value depends on the different types and is
3948
Value type | return value
3949
----------- | -------------
3950
null | @c 0 (same as size())
3951
boolean | @c 1 (same as size())
3952
string | @c 1 (same as size())
3953
number | @c 1 (same as size())
3954
object | result of function object_t::max_size()
3955
array | result of function array_t::max_size()
3957
@complexity Constant, as long as @ref array_t and @ref object_t satisfy the
3958
Container concept; that is, their max_size() functions have constant
3961
@requirement This function satisfies the Container requirements:
3962
- The complexity is constant.
3963
- Has the semantics of returning `b.size()` where `b` is the largest
3964
possible JSON value.
3966
@liveexample{The following code calls @ref max_size on the different value
3967
types. Note the output is implementation specific.,max_size}
3969
@since version 1.0.0
3971
size_type max_size() const noexcept
3975
case value_t::array:
3977
return m_value.array->max_size();
3980
case value_t::object:
3982
return m_value.object->max_size();
3987
// all other types have max_size() == size()
4004
@brief clears the contents
4006
Clears the content of a JSON value and resets it to the default value as
4007
if @ref basic_json(value_t) would have been called:
4009
Value type | initial value
4010
----------- | -------------
4018
@note Floating-point numbers are set to `0.0` which will be serialized to
4019
`0`. The vale type remains @ref number_float_t.
4021
@complexity Linear in the size of the JSON value.
4023
@liveexample{The example below shows the effect of @ref clear to different
4026
@since version 1.0.0
4028
void clear() noexcept
4032
case value_t::number_integer:
4034
m_value.number_integer = 0;
4038
case value_t::number_float:
4040
m_value.number_float = 0.0;
4044
case value_t::boolean:
4046
m_value.boolean = false;
4050
case value_t::string:
4052
m_value.string->clear();
4056
case value_t::array:
4058
m_value.array->clear();
4062
case value_t::object:
4064
m_value.object->clear();
4076
@brief add an object to an array
4078
Appends the given element @a val to the end of the JSON value. If the
4079
function is called on a JSON null value, an empty array is created before
4082
@param val the value to add to the JSON array
4084
@throw std::domain_error when called on a type other than JSON array or
4085
null; example: `"cannot use push_back() with number"`
4087
@complexity Amortized constant.
4089
@liveexample{The example shows how `push_back` and `+=` can be used to add
4090
elements to a JSON array. Note how the `null` value was silently converted
4091
to a JSON array.,push_back}
4093
@since version 1.0.0
4095
void push_back(basic_json&& val)
4097
// push_back only works for null objects or arrays
4098
if (not(is_null() or is_array()))
4100
throw std::domain_error("cannot use push_back() with " + type_name());
4103
// transform null object into an array
4106
m_type = value_t::array;
4107
m_value = value_t::array;
4110
// add element to array (move semantics)
4111
m_value.array->push_back(std::move(val));
4112
// invalidate object
4113
val.m_type = value_t::null;
4117
@brief add an object to an array
4118
@copydoc push_back(basic_json&&)
4120
reference operator+=(basic_json&& val)
4122
push_back(std::move(val));
4127
@brief add an object to an array
4128
@copydoc push_back(basic_json&&)
4130
void push_back(const basic_json& val)
4132
// push_back only works for null objects or arrays
4133
if (not(is_null() or is_array()))
4135
throw std::domain_error("cannot use push_back() with " + type_name());
4138
// transform null object into an array
4141
m_type = value_t::array;
4142
m_value = value_t::array;
4145
// add element to array
4146
m_value.array->push_back(val);
4150
@brief add an object to an array
4151
@copydoc push_back(basic_json&&)
4153
reference operator+=(const basic_json& val)
4160
@brief add an object to an object
4162
Inserts the given element @a val to the JSON object. If the function is
4163
called on a JSON null value, an empty object is created before inserting @a
4166
@param[in] val the value to add to the JSON object
4168
@throw std::domain_error when called on a type other than JSON object or
4169
null; example: `"cannot use push_back() with number"`
4171
@complexity Logarithmic in the size of the container, O(log(`size()`)).
4173
@liveexample{The example shows how `push_back` and `+=` can be used to add
4174
elements to a JSON object. Note how the `null` value was silently converted
4175
to a JSON object.,push_back__object_t__value}
4177
@since version 1.0.0
4179
void push_back(const typename object_t::value_type& val)
4181
// push_back only works for null objects or objects
4182
if (not(is_null() or is_object()))
4184
throw std::domain_error("cannot use push_back() with " + type_name());
4187
// transform null object into an object
4190
m_type = value_t::object;
4191
m_value = value_t::object;
4194
// add element to array
4195
m_value.object->insert(val);
4199
@brief add an object to an object
4200
@copydoc push_back(const typename object_t::value_type&)
4202
reference operator+=(const typename object_t::value_type& val)
4205
return operator[](val.first);
4209
@brief inserts element
4211
Inserts element @a val before iterator @a pos.
4213
@param[in] pos iterator before which the content will be inserted; may be
4215
@param[in] val element to insert
4216
@return iterator pointing to the inserted @a val.
4218
@throw std::domain_error if called on JSON values other than arrays;
4219
example: `"cannot use insert() with string"`
4220
@throw std::domain_error if @a pos is not an iterator of *this; example:
4221
`"iterator does not fit current value"`
4223
@complexity Constant plus linear in the distance between pos and end of the
4226
@liveexample{The example shows how insert is used.,insert}
4228
@since version 1.0.0
4230
iterator insert(const_iterator pos, const basic_json& val)
4232
// insert only works for arrays
4235
// check if iterator pos fits to this JSON value
4236
if (pos.m_object != this)
4238
throw std::domain_error("iterator does not fit current value");
4241
// insert to array and return iterator
4242
iterator result(this);
4243
result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, val);
4248
throw std::domain_error("cannot use insert() with " + type_name());
4253
@brief inserts element
4254
@copydoc insert(const_iterator, const basic_json&)
4256
iterator insert(const_iterator pos, basic_json&& val)
4258
return insert(pos, val);
4262
@brief inserts elements
4264
Inserts @a cnt copies of @a val before iterator @a pos.
4266
@param[in] pos iterator before which the content will be inserted; may be
4268
@param[in] cnt number of copies of @a val to insert
4269
@param[in] val element to insert
4270
@return iterator pointing to the first element inserted, or @a pos if
4273
@throw std::domain_error if called on JSON values other than arrays;
4274
example: `"cannot use insert() with string"`
4275
@throw std::domain_error if @a pos is not an iterator of *this; example:
4276
`"iterator does not fit current value"`
4278
@complexity Linear in @a cnt plus linear in the distance between @a pos
4279
and end of the container.
4281
@liveexample{The example shows how insert is used.,insert__count}
4283
@since version 1.0.0
4285
iterator insert(const_iterator pos, size_type cnt, const basic_json& val)
4287
// insert only works for arrays
4290
// check if iterator pos fits to this JSON value
4291
if (pos.m_object != this)
4293
throw std::domain_error("iterator does not fit current value");
4296
// insert to array and return iterator
4297
iterator result(this);
4298
result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val);
4303
throw std::domain_error("cannot use insert() with " + type_name());
4308
@brief inserts elements
4310
Inserts elements from range `[first, last)` before iterator @a pos.
4312
@param[in] pos iterator before which the content will be inserted; may be
4314
@param[in] first begin of the range of elements to insert
4315
@param[in] last end of the range of elements to insert
4317
@throw std::domain_error if called on JSON values other than arrays;
4318
example: `"cannot use insert() with string"`
4319
@throw std::domain_error if @a pos is not an iterator of *this; example:
4320
`"iterator does not fit current value"`
4321
@throw std::domain_error if @a first and @a last do not belong to the same
4322
JSON value; example: `"iterators do not fit"`
4323
@throw std::domain_error if @a first or @a last are iterators into
4324
container for which insert is called; example: `"passed iterators may not
4325
belong to container"`
4327
@return iterator pointing to the first element inserted, or @a pos if
4330
@complexity Linear in `std::distance(first, last)` plus linear in the
4331
distance between @a pos and end of the container.
4333
@liveexample{The example shows how insert is used.,insert__range}
4335
@since version 1.0.0
4337
iterator insert(const_iterator pos, const_iterator first, const_iterator last)
4339
// insert only works for arrays
4342
throw std::domain_error("cannot use insert() with " + type_name());
4345
// check if iterator pos fits to this JSON value
4346
if (pos.m_object != this)
4348
throw std::domain_error("iterator does not fit current value");
4351
if (first.m_object != last.m_object)
4353
throw std::domain_error("iterators do not fit");
4356
if (first.m_object == this or last.m_object == this)
4358
throw std::domain_error("passed iterators may not belong to container");
4361
// insert to array and return iterator
4362
iterator result(this);
4363
result.m_it.array_iterator = m_value.array->insert(
4364
pos.m_it.array_iterator,
4365
first.m_it.array_iterator,
4366
last.m_it.array_iterator);
4371
@brief inserts elements
4373
Inserts elements from initializer list @a ilist before iterator @a pos.
4375
@param[in] pos iterator before which the content will be inserted; may be
4377
@param[in] ilist initializer list to insert the values from
4379
@throw std::domain_error if called on JSON values other than arrays;
4380
example: `"cannot use insert() with string"`
4381
@throw std::domain_error if @a pos is not an iterator of *this; example:
4382
`"iterator does not fit current value"`
4384
@return iterator pointing to the first element inserted, or @a pos if
4387
@complexity Linear in `ilist.size()` plus linear in the distance between @a
4388
pos and end of the container.
4390
@liveexample{The example shows how insert is used.,insert__ilist}
4392
@since version 1.0.0
4394
iterator insert(const_iterator pos, std::initializer_list<basic_json> ilist)
4396
// insert only works for arrays
4399
throw std::domain_error("cannot use insert() with " + type_name());
4402
// check if iterator pos fits to this JSON value
4403
if (pos.m_object != this)
4405
throw std::domain_error("iterator does not fit current value");
4408
// insert to array and return iterator
4409
iterator result(this);
4410
result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, ilist);
4415
@brief exchanges the values
4417
Exchanges the contents of the JSON value with those of @a other. Does not
4418
invoke any move, copy, or swap operations on individual elements. All
4419
iterators and references remain valid. The past-the-end iterator is
4422
@param[in,out] other JSON value to exchange the contents with
4424
@complexity Constant.
4426
@liveexample{The example below shows how JSON arrays can be
4427
swapped.,swap__reference}
4429
@since version 1.0.0
4431
void swap(reference other) noexcept (
4432
std::is_nothrow_move_constructible<value_t>::value and
4433
std::is_nothrow_move_assignable<value_t>::value and
4434
std::is_nothrow_move_constructible<json_value>::value and
4435
std::is_nothrow_move_assignable<json_value>::value
4438
std::swap(m_type, other.m_type);
4439
std::swap(m_value, other.m_value);
4443
@brief exchanges the values
4445
Exchanges the contents of a JSON array with those of @a other. Does not
4446
invoke any move, copy, or swap operations on individual elements. All
4447
iterators and references remain valid. The past-the-end iterator is
4450
@param[in,out] other array to exchange the contents with
4452
@throw std::domain_error when JSON value is not an array; example: `"cannot
4453
use swap() with string"`
4455
@complexity Constant.
4457
@liveexample{The example below shows how JSON values can be
4458
swapped.,swap__array_t}
4460
@since version 1.0.0
4462
void swap(array_t& other)
4464
// swap only works for arrays
4467
std::swap(*(m_value.array), other);
4471
throw std::domain_error("cannot use swap() with " + type_name());
4476
@brief exchanges the values
4478
Exchanges the contents of a JSON object with those of @a other. Does not
4479
invoke any move, copy, or swap operations on individual elements. All
4480
iterators and references remain valid. The past-the-end iterator is
4483
@param[in,out] other object to exchange the contents with
4485
@throw std::domain_error when JSON value is not an object; example:
4486
`"cannot use swap() with string"`
4488
@complexity Constant.
4490
@liveexample{The example below shows how JSON values can be
4491
swapped.,swap__object_t}
4493
@since version 1.0.0
4495
void swap(object_t& other)
4497
// swap only works for objects
4500
std::swap(*(m_value.object), other);
4504
throw std::domain_error("cannot use swap() with " + type_name());
4509
@brief exchanges the values
4511
Exchanges the contents of a JSON string with those of @a other. Does not
4512
invoke any move, copy, or swap operations on individual elements. All
4513
iterators and references remain valid. The past-the-end iterator is
4516
@param[in,out] other string to exchange the contents with
4518
@throw std::domain_error when JSON value is not a string; example: `"cannot
4519
use swap() with boolean"`
4521
@complexity Constant.
4523
@liveexample{The example below shows how JSON values can be
4524
swapped.,swap__string_t}
4526
@since version 1.0.0
4528
void swap(string_t& other)
4530
// swap only works for strings
4533
std::swap(*(m_value.string), other);
4537
throw std::domain_error("cannot use swap() with " + type_name());
4544
//////////////////////////////////////////
4545
// lexicographical comparison operators //
4546
//////////////////////////////////////////
4548
/// @name lexicographical comparison operators
4553
@brief comparison operator for JSON types
4555
Returns an ordering that is similar to Python:
4556
- order: null < boolean < number < object < array < string
4557
- furthermore, each type is not smaller than itself
4559
@since version 1.0.0
4561
friend bool operator<(const value_t lhs, const value_t rhs)
4563
static constexpr std::array<uint8_t, 7> order = {{
4574
// discarded values are not comparable
4575
if (lhs == value_t::discarded or rhs == value_t::discarded)
4580
return order[static_cast<std::size_t>(lhs)] < order[static_cast<std::size_t>(rhs)];
4585
@brief comparison: equal
4587
Compares two JSON values for equality according to the following rules:
4588
- Two JSON values are equal if (1) they are from the same type and (2)
4589
their stored values are the same.
4590
- Integer and floating-point numbers are automatically converted before
4591
comparison. Floating-point numbers are compared indirectly: two
4592
floating-point numbers `f1` and `f2` are considered equal if neither
4593
`f1 > f2` nor `f2 > f1` holds.
4594
- Two JSON null values are equal.
4596
@param[in] lhs first JSON value to consider
4597
@param[in] rhs second JSON value to consider
4598
@return whether the values @a lhs and @a rhs are equal
4602
@liveexample{The example demonstrates comparing several JSON
4603
types.,operator__equal}
4605
@since version 1.0.0
4607
friend bool operator==(const_reference lhs, const_reference rhs) noexcept
4609
const auto lhs_type = lhs.type();
4610
const auto rhs_type = rhs.type();
4612
if (lhs_type == rhs_type)
4616
case value_t::array:
4617
return *lhs.m_value.array == *rhs.m_value.array;
4618
case value_t::object:
4619
return *lhs.m_value.object == *rhs.m_value.object;
4622
case value_t::string:
4623
return *lhs.m_value.string == *rhs.m_value.string;
4624
case value_t::boolean:
4625
return lhs.m_value.boolean == rhs.m_value.boolean;
4626
case value_t::number_integer:
4627
return lhs.m_value.number_integer == rhs.m_value.number_integer;
4628
case value_t::number_float:
4629
return approx(lhs.m_value.number_float, rhs.m_value.number_float);
4634
else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
4636
return approx(static_cast<number_float_t>(lhs.m_value.number_integer),
4637
rhs.m_value.number_float);
4639
else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
4641
return approx(lhs.m_value.number_float,
4642
static_cast<number_float_t>(rhs.m_value.number_integer));
4648
@brief comparison: equal
4650
The functions compares the given JSON value against a null pointer. As the
4651
null pointer can be used to initialize a JSON value to null, a comparison
4652
of JSON value @a v with a null pointer should be equivalent to call
4655
@param[in] v JSON value to consider
4656
@return whether @a v is null
4658
@complexity Constant.
4660
@liveexample{The example compares several JSON types to the null pointer.
4661
,operator__equal__nullptr_t}
4663
@since version 1.0.0
4665
friend bool operator==(const_reference v, std::nullptr_t) noexcept
4671
@brief comparison: equal
4672
@copydoc operator==(const_reference, std::nullptr_t)
4674
friend bool operator==(std::nullptr_t, const_reference v) noexcept
4680
@brief comparison: not equal
4682
Compares two JSON values for inequality by calculating `not (lhs == rhs)`.
4684
@param[in] lhs first JSON value to consider
4685
@param[in] rhs second JSON value to consider
4686
@return whether the values @a lhs and @a rhs are not equal
4690
@liveexample{The example demonstrates comparing several JSON
4691
types.,operator__notequal}
4693
@since version 1.0.0
4695
friend bool operator!=(const_reference lhs, const_reference rhs) noexcept
4697
return not (lhs == rhs);
4701
@brief comparison: not equal
4703
The functions compares the given JSON value against a null pointer. As the
4704
null pointer can be used to initialize a JSON value to null, a comparison
4705
of JSON value @a v with a null pointer should be equivalent to call
4708
@param[in] v JSON value to consider
4709
@return whether @a v is not null
4711
@complexity Constant.
4713
@liveexample{The example compares several JSON types to the null pointer.
4714
,operator__notequal__nullptr_t}
4716
@since version 1.0.0
4718
friend bool operator!=(const_reference v, std::nullptr_t) noexcept
4720
return not v.is_null();
4724
@brief comparison: not equal
4725
@copydoc operator!=(const_reference, std::nullptr_t)
4727
friend bool operator!=(std::nullptr_t, const_reference v) noexcept
4729
return not v.is_null();
4733
@brief comparison: less than
4735
Compares whether one JSON value @a lhs is less than another JSON value @a
4736
rhs according to the following rules:
4737
- If @a lhs and @a rhs have the same type, the values are compared using
4738
the default `<` operator.
4739
- Integer and floating-point numbers are automatically converted before
4741
- In case @a lhs and @a rhs have different types, the values are ignored
4742
and the order of the types is considered, see
4743
@ref operator<(const value_t, const value_t).
4745
@param[in] lhs first JSON value to consider
4746
@param[in] rhs second JSON value to consider
4747
@return whether @a lhs is less than @a rhs
4751
@liveexample{The example demonstrates comparing several JSON
4752
types.,operator__less}
4754
@since version 1.0.0
4756
friend bool operator<(const_reference lhs, const_reference rhs) noexcept
4758
const auto lhs_type = lhs.type();
4759
const auto rhs_type = rhs.type();
4761
if (lhs_type == rhs_type)
4765
case value_t::array:
4766
return *lhs.m_value.array < *rhs.m_value.array;
4767
case value_t::object:
4768
return *lhs.m_value.object < *rhs.m_value.object;
4771
case value_t::string:
4772
return *lhs.m_value.string < *rhs.m_value.string;
4773
case value_t::boolean:
4774
return lhs.m_value.boolean < rhs.m_value.boolean;
4775
case value_t::number_integer:
4776
return lhs.m_value.number_integer < rhs.m_value.number_integer;
4777
case value_t::number_float:
4778
return lhs.m_value.number_float < rhs.m_value.number_float;
4783
else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float)
4785
return static_cast<number_float_t>(lhs.m_value.number_integer) <
4786
rhs.m_value.number_float;
4788
else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer)
4790
return lhs.m_value.number_float <
4791
static_cast<number_float_t>(rhs.m_value.number_integer);
4794
// We only reach this line if we cannot compare values. In that case,
4795
// we compare types. Note we have to call the operator explicitly,
4796
// because MSVC has problems otherwise.
4797
return operator<(lhs_type, rhs_type);
4801
@brief comparison: less than or equal
4803
Compares whether one JSON value @a lhs is less than or equal to another
4804
JSON value by calculating `not (rhs < lhs)`.
4806
@param[in] lhs first JSON value to consider
4807
@param[in] rhs second JSON value to consider
4808
@return whether @a lhs is less than or equal to @a rhs
4812
@liveexample{The example demonstrates comparing several JSON
4813
types.,operator__greater}
4815
@since version 1.0.0
4817
friend bool operator<=(const_reference lhs, const_reference rhs) noexcept
4819
return not (rhs < lhs);
4823
@brief comparison: greater than
4825
Compares whether one JSON value @a lhs is greater than another
4826
JSON value by calculating `not (lhs <= rhs)`.
4828
@param[in] lhs first JSON value to consider
4829
@param[in] rhs second JSON value to consider
4830
@return whether @a lhs is greater than to @a rhs
4834
@liveexample{The example demonstrates comparing several JSON
4835
types.,operator__lessequal}
4837
@since version 1.0.0
4839
friend bool operator>(const_reference lhs, const_reference rhs) noexcept
4841
return not (lhs <= rhs);
4845
@brief comparison: greater than or equal
4847
Compares whether one JSON value @a lhs is greater than or equal to another
4848
JSON value by calculating `not (lhs < rhs)`.
4850
@param[in] lhs first JSON value to consider
4851
@param[in] rhs second JSON value to consider
4852
@return whether @a lhs is greater than or equal to @a rhs
4856
@liveexample{The example demonstrates comparing several JSON
4857
types.,operator__greaterequal}
4859
@since version 1.0.0
4861
friend bool operator>=(const_reference lhs, const_reference rhs) noexcept
4863
return not (lhs < rhs);
4873
/// @name serialization
4877
@brief serialize to stream
4879
Serialize the given JSON value @a j to the output stream @a o. The JSON
4880
value will be serialized using the @ref dump member function. The
4881
indentation of the output can be controlled with the member variable
4882
`width` of the output stream @a o. For instance, using the manipulator
4883
`std::setw(4)` on @a o sets the indentation level to `4` and the
4884
serialization result is the same as calling `dump(4)`.
4886
@param[in,out] o stream to serialize to
4887
@param[in] j JSON value to serialize
4889
@return the stream @a o
4893
@liveexample{The example below shows the serialization with different
4894
parameters to `width` to adjust the indentation level.,operator_serialize}
4896
@since version 1.0.0
4898
friend std::ostream& operator<<(std::ostream& o, const basic_json& j)
4900
// read width member and use it as indentation parameter if nonzero
4901
const bool pretty_print = (o.width() > 0);
4902
const auto indentation = (pretty_print ? o.width() : 0);
4904
// reset width to 0 for subsequent calls to this stream
4907
// do the actual serialization
4908
j.dump(o, pretty_print, static_cast<unsigned int>(indentation));
4913
@brief serialize to stream
4914
@copydoc operator<<(std::ostream&, const basic_json&)
4916
friend std::ostream& operator>>(const basic_json& j, std::ostream& o)
4924
/////////////////////
4925
// deserialization //
4926
/////////////////////
4928
/// @name deserialization
4932
@brief deserialize from string
4934
@param[in] s string to read a serialized JSON value from
4935
@param[in] cb a parser callback function of type @ref parser_callback_t
4936
which is used to control the deserialization by filtering unwanted values
4939
@return result of the deserialization
4941
@complexity Linear in the length of the input. The parser is a predictive
4942
LL(1) parser. The complexity can be higher if the parser callback function
4943
@a cb has a super-linear complexity.
4945
@note A UTF-8 byte order mark is silently ignored.
4947
@liveexample{The example below demonstrates the parse function with and
4948
without callback function.,parse__string__parser_callback_t}
4950
@sa @ref parse(std::istream&, parser_callback_t) for a version that reads
4951
from an input stream
4953
@since version 1.0.0
4955
static basic_json parse(const string_t& s, parser_callback_t cb = nullptr)
4957
return parser(s, cb).parse();
4961
@brief deserialize from stream
4963
@param[in,out] i stream to read a serialized JSON value from
4964
@param[in] cb a parser callback function of type @ref parser_callback_t
4965
which is used to control the deserialization by filtering unwanted values
4968
@return result of the deserialization
4970
@complexity Linear in the length of the input. The parser is a predictive
4971
LL(1) parser. The complexity can be higher if the parser callback function
4972
@a cb has a super-linear complexity.
4974
@note A UTF-8 byte order mark is silently ignored.
4976
@liveexample{The example below demonstrates the parse function with and
4977
without callback function.,parse__istream__parser_callback_t}
4979
@sa @ref parse(const string_t&, parser_callback_t) for a version that reads
4982
@since version 1.0.0
4984
static basic_json parse(std::istream& i, parser_callback_t cb = nullptr)
4986
return parser(i, cb).parse();
4990
@copydoc parse(std::istream&, parser_callback_t)
4992
static basic_json parse(std::istream&& i, parser_callback_t cb = nullptr)
4994
return parser(i, cb).parse();
4998
@brief deserialize from stream
5000
Deserializes an input stream to a JSON value.
5002
@param[in,out] i input stream to read a serialized JSON value from
5003
@param[in,out] j JSON value to write the deserialized input to
5005
@throw std::invalid_argument in case of parse errors
5007
@complexity Linear in the length of the input. The parser is a predictive
5010
@note A UTF-8 byte order mark is silently ignored.
5012
@liveexample{The example below shows how a JSON value is constructed by
5013
reading a serialization from a stream.,operator_deserialize}
5015
@sa parse(std::istream&, parser_callback_t) for a variant with a parser
5016
callback function to filter values while parsing
5018
@since version 1.0.0
5020
friend std::istream& operator<<(basic_json& j, std::istream& i)
5022
j = parser(i).parse();
5027
@brief deserialize from stream
5028
@copydoc operator<<(basic_json&, std::istream&)
5030
friend std::istream& operator>>(std::istream& i, basic_json& j)
5032
j = parser(i).parse();
5040
///////////////////////////
5041
// convenience functions //
5042
///////////////////////////
5044
/// return the type as string
5045
string_t type_name() const
5051
case value_t::object:
5053
case value_t::array:
5055
case value_t::string:
5057
case value_t::boolean:
5059
case value_t::discarded:
5067
@brief calculates the extra space to escape a JSON string
5069
@param[in] s the string to escape
5070
@return the number of characters required to escape string @a s
5072
@complexity Linear in the length of string @a s.
5074
static std::size_t extra_space(const string_t& s) noexcept
5076
std::size_t result = 0;
5078
for (const auto& c : s)
5090
// from c (1 byte) to \x (2 bytes)
5097
if (c >= 0x00 and c <= 0x1f)
5099
// from c (1 byte) to \uxxxx (6 bytes)
5111
@brief escape a string
5113
Escape a string by replacing certain special characters by a sequence of an
5114
escape character (backslash) and another character and other control
5115
characters by a sequence of "\u" followed by a four-digit hex
5118
@param[in] s the string to escape
5119
@return the escaped string
5121
@complexity Linear in the length of string @a s.
5123
static string_t escape_string(const string_t& s) noexcept
5125
const auto space = extra_space(s);
5131
// create a result string of necessary size
5132
string_t result(s.size() + space, '\\');
5133
std::size_t pos = 0;
5135
for (const auto& c : s)
5139
// quotation mark (0x22)
5142
result[pos + 1] = '"';
5147
// reverse solidus (0x5c)
5150
// nothing to change
5158
result[pos + 1] = 'b';
5166
result[pos + 1] = 'f';
5174
result[pos + 1] = 'n';
5179
// carriage return (0x0d)
5182
result[pos + 1] = 'r';
5187
// horizontal tab (0x09)
5190
result[pos + 1] = 't';
5197
if (c >= 0x00 and c <= 0x1f)
5199
// convert a number 0..15 to its hex representation (0..f)
5200
auto hexify = [](const char v) -> char
5202
return (v < 10) ? ('0' + v) : ('a' + v - 10);
5205
// print character c as \uxxxx
5207
{ 'u', '0', '0', hexify(c >> 4), hexify(c & 0x0f)
5217
// all other characters are added as-is
5229
@brief internal implementation of the serialization function
5231
This function is called by the public member function dump and organizes
5232
the serializaion internally. The indentation level is propagated as
5233
additional parameter. In case of arrays and objects, the function is called
5234
recursively. Note that
5236
- strings and object keys are escaped using escape_string()
5237
- integer numbers are converted implictly via operator<<
5238
- floating-point numbers are converted to a string using "%g" format
5240
@param[out] o stream to write to
5241
@param[in] pretty_print whether the output shall be pretty-printed
5242
@param[in] indent_step the indent level
5243
@param[in] current_indent the current indent level (only used internally)
5245
void dump(std::ostream& o,
5246
const bool pretty_print,
5247
const unsigned int indent_step,
5248
const unsigned int current_indent = 0) const
5250
// variable to hold indentation for recursive calls
5251
unsigned int new_indent = current_indent;
5255
case value_t::object:
5257
if (m_value.object->empty())
5265
// increase indentation
5268
new_indent += indent_step;
5272
for (auto i = m_value.object->cbegin(); i != m_value.object->cend(); ++i)
5274
if (i != m_value.object->cbegin())
5276
o << (pretty_print ? ",\n" : ",");
5278
o << string_t(new_indent, ' ') << "\""
5279
<< escape_string(i->first) << "\":"
5280
<< (pretty_print ? " " : "");
5281
i->second.dump(o, pretty_print, indent_step, new_indent);
5284
// decrease indentation
5287
new_indent -= indent_step;
5291
o << string_t(new_indent, ' ') + "}";
5295
case value_t::array:
5297
if (m_value.array->empty())
5305
// increase indentation
5308
new_indent += indent_step;
5312
for (auto i = m_value.array->cbegin(); i != m_value.array->cend(); ++i)
5314
if (i != m_value.array->cbegin())
5316
o << (pretty_print ? ",\n" : ",");
5318
o << string_t(new_indent, ' ');
5319
i->dump(o, pretty_print, indent_step, new_indent);
5322
// decrease indentation
5325
new_indent -= indent_step;
5329
o << string_t(new_indent, ' ') << "]";
5333
case value_t::string:
5335
o << string_t("\"") << escape_string(*m_value.string) << "\"";
5339
case value_t::boolean:
5341
o << (m_value.boolean ? "true" : "false");
5345
case value_t::number_integer:
5347
o << m_value.number_integer;
5351
case value_t::number_float:
5353
// 15 digits of precision allows round-trip IEEE 754
5354
// string->double->string; to be safe, we read this value from
5355
// std::numeric_limits<number_float_t>::digits10
5356
o << std::setprecision(std::numeric_limits<number_float_t>::digits10) << m_value.number_float;
5360
case value_t::discarded:
5375
//////////////////////
5376
// member variables //
5377
//////////////////////
5379
/// the type of the current element
5380
value_t m_type = value_t::null;
5382
/// the value of the current element
5383
json_value m_value = {};
5392
@brief an iterator for primitive JSON types
5394
This class models an iterator for primitive JSON types (boolean, number,
5395
string). It's only purpose is to allow the iterator/const_iterator classes
5396
to "iterate" over primitive values. Internally, the iterator is modeled by
5397
a `difference_type` variable. Value begin_value (`0`) models the begin,
5398
end_value (`1`) models past the end.
5400
class primitive_iterator_t
5403
/// set iterator to a defined beginning
5409
/// set iterator to a defined past the end
5415
/// return whether the iterator can be dereferenced
5416
bool is_begin() const
5418
return (m_it == begin_value);
5421
/// return whether the iterator is at end
5424
return (m_it == end_value);
5427
/// return reference to the value to change and compare
5428
operator difference_type& ()
5433
/// return value to compare
5434
operator difference_type () const
5440
static constexpr difference_type begin_value = 0;
5441
static constexpr difference_type end_value = begin_value + 1;
5443
/// iterator as signed integer type
5444
difference_type m_it = std::numeric_limits<std::ptrdiff_t>::denorm_min();
5448
@brief an iterator value
5450
@note This structure could easily be a union, but MSVC currently does not
5451
allow unions members with complex constructors, see
5452
https://github.com/nlohmann/json/pull/105.
5454
struct internal_iterator
5456
/// iterator for JSON objects
5457
typename object_t::iterator object_iterator;
5458
/// iterator for JSON arrays
5459
typename array_t::iterator array_iterator;
5460
/// generic iterator for all other types
5461
primitive_iterator_t primitive_iterator;
5463
/// create an uninitialized internal_iterator
5465
: object_iterator(), array_iterator(), primitive_iterator()
5469
/// proxy class for the iterator_wrapper functions
5470
template<typename IteratorType>
5471
class iteration_proxy
5474
/// helper class for iteration
5475
class iteration_proxy_internal
5479
IteratorType anchor;
5480
/// an index for arrays (used to create key names)
5481
size_t array_index = 0;
5484
iteration_proxy_internal(IteratorType it)
5488
/// dereference operator (needed for range-based for)
5489
iteration_proxy_internal& operator*()
5494
/// increment operator (needed for range-based for)
5495
iteration_proxy_internal& operator++()
5503
/// inequality operator (needed for range-based for)
5504
bool operator!= (const iteration_proxy_internal& o) const
5506
return anchor != o.anchor;
5509
/// return key of the iterator
5510
typename basic_json::string_t key() const
5512
switch (anchor.m_object->type())
5514
// use integer array index as key
5515
case value_t::array:
5517
return std::to_string(array_index);
5520
// use key from the object
5521
case value_t::object:
5523
return anchor.key();
5526
// use an empty key for all primitive types
5534
/// return value of the iterator
5535
typename IteratorType::reference value() const
5537
return anchor.value();
5541
/// the container to iterate
5542
typename IteratorType::reference container;
5545
/// construct iteration proxy from a container
5546
iteration_proxy(typename IteratorType::reference cont)
5550
/// return iterator begin (needed for range-based for)
5551
iteration_proxy_internal begin()
5553
return iteration_proxy_internal(container.begin());
5556
/// return iterator end (needed for range-based for)
5557
iteration_proxy_internal end()
5559
return iteration_proxy_internal(container.end());
5565
@brief a const random access iterator for the @ref basic_json class
5567
This class implements a const iterator for the @ref basic_json class. From
5568
this class, the @ref iterator class is derived.
5570
@requirement The class satisfies the following concept requirements:
5571
- [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
5572
The iterator that can be moved to point (forward and backward) to any
5573
element in constant time.
5575
@since version 1.0.0
5577
class const_iterator : public std::iterator<std::random_access_iterator_tag, const basic_json>
5579
/// allow basic_json to access private members
5580
friend class basic_json;
5583
/// the type of the values when the iterator is dereferenced
5584
using value_type = typename basic_json::value_type;
5585
/// a type to represent differences between iterators
5586
using difference_type = typename basic_json::difference_type;
5587
/// defines a pointer to the type iterated over (value_type)
5588
using pointer = typename basic_json::const_pointer;
5589
/// defines a reference to the type iterated over (value_type)
5590
using reference = typename basic_json::const_reference;
5591
/// the category of the iterator
5592
using iterator_category = std::bidirectional_iterator_tag;
5594
/// default constructor
5595
const_iterator() = default;
5597
/// constructor for a given JSON instance
5598
const_iterator(pointer object) : m_object(object)
5600
switch (m_object->m_type)
5602
case basic_json::value_t::object:
5604
m_it.object_iterator = typename object_t::iterator();
5608
case basic_json::value_t::array:
5610
m_it.array_iterator = typename array_t::iterator();
5616
m_it.primitive_iterator = primitive_iterator_t();
5622
/// copy constructor given a nonconst iterator
5623
const_iterator(const iterator& other) : m_object(other.m_object)
5625
switch (m_object->m_type)
5627
case basic_json::value_t::object:
5629
m_it.object_iterator = other.m_it.object_iterator;
5633
case basic_json::value_t::array:
5635
m_it.array_iterator = other.m_it.array_iterator;
5641
m_it.primitive_iterator = other.m_it.primitive_iterator;
5647
/// copy constructor
5648
const_iterator(const const_iterator& other) noexcept
5649
: m_object(other.m_object), m_it(other.m_it)
5653
const_iterator& operator=(const_iterator other) noexcept(
5654
std::is_nothrow_move_constructible<pointer>::value and
5655
std::is_nothrow_move_assignable<pointer>::value and
5656
std::is_nothrow_move_constructible<internal_iterator>::value and
5657
std::is_nothrow_move_assignable<internal_iterator>::value
5660
std::swap(m_object, other.m_object);
5661
std::swap(m_it, other.m_it);
5666
/// set the iterator to the first value
5669
switch (m_object->m_type)
5671
case basic_json::value_t::object:
5673
m_it.object_iterator = m_object->m_value.object->begin();
5677
case basic_json::value_t::array:
5679
m_it.array_iterator = m_object->m_value.array->begin();
5683
case basic_json::value_t::null:
5685
// set to end so begin()==end() is true: null is empty
5686
m_it.primitive_iterator.set_end();
5692
m_it.primitive_iterator.set_begin();
5698
/// set the iterator past the last value
5701
switch (m_object->m_type)
5703
case basic_json::value_t::object:
5705
m_it.object_iterator = m_object->m_value.object->end();
5709
case basic_json::value_t::array:
5711
m_it.array_iterator = m_object->m_value.array->end();
5717
m_it.primitive_iterator.set_end();
5724
/// return a reference to the value pointed to by the iterator
5725
reference operator*() const
5727
switch (m_object->m_type)
5729
case basic_json::value_t::object:
5731
return m_it.object_iterator->second;
5734
case basic_json::value_t::array:
5736
return *m_it.array_iterator;
5739
case basic_json::value_t::null:
5741
throw std::out_of_range("cannot get value");
5746
if (m_it.primitive_iterator.is_begin())
5752
throw std::out_of_range("cannot get value");
5758
/// dereference the iterator
5759
pointer operator->() const
5761
switch (m_object->m_type)
5763
case basic_json::value_t::object:
5765
return &(m_it.object_iterator->second);
5768
case basic_json::value_t::array:
5770
return &*m_it.array_iterator;
5775
if (m_it.primitive_iterator.is_begin())
5781
throw std::out_of_range("cannot get value");
5787
/// post-increment (it++)
5788
const_iterator operator++(int)
5790
auto result = *this;
5795
/// pre-increment (++it)
5796
const_iterator& operator++()
5798
switch (m_object->m_type)
5800
case basic_json::value_t::object:
5802
++m_it.object_iterator;
5806
case basic_json::value_t::array:
5808
++m_it.array_iterator;
5814
++m_it.primitive_iterator;
5822
/// post-decrement (it--)
5823
const_iterator operator--(int)
5825
auto result = *this;
5830
/// pre-decrement (--it)
5831
const_iterator& operator--()
5833
switch (m_object->m_type)
5835
case basic_json::value_t::object:
5837
--m_it.object_iterator;
5841
case basic_json::value_t::array:
5843
--m_it.array_iterator;
5849
--m_it.primitive_iterator;
5857
/// comparison: equal
5858
bool operator==(const const_iterator& other) const
5860
// if objects are not the same, the comparison is undefined
5861
if (m_object != other.m_object)
5863
throw std::domain_error("cannot compare iterators of different containers");
5866
switch (m_object->m_type)
5868
case basic_json::value_t::object:
5870
return (m_it.object_iterator == other.m_it.object_iterator);
5873
case basic_json::value_t::array:
5875
return (m_it.array_iterator == other.m_it.array_iterator);
5880
return (m_it.primitive_iterator == other.m_it.primitive_iterator);
5885
/// comparison: not equal
5886
bool operator!=(const const_iterator& other) const
5888
return not operator==(other);
5891
/// comparison: smaller
5892
bool operator<(const const_iterator& other) const
5894
// if objects are not the same, the comparison is undefined
5895
if (m_object != other.m_object)
5897
throw std::domain_error("cannot compare iterators of different containers");
5900
switch (m_object->m_type)
5902
case basic_json::value_t::object:
5904
throw std::domain_error("cannot compare order of object iterators");
5907
case basic_json::value_t::array:
5909
return (m_it.array_iterator < other.m_it.array_iterator);
5914
return (m_it.primitive_iterator < other.m_it.primitive_iterator);
5919
/// comparison: less than or equal
5920
bool operator<=(const const_iterator& other) const
5922
return not other.operator < (*this);
5925
/// comparison: greater than
5926
bool operator>(const const_iterator& other) const
5928
return not operator<=(other);
5931
/// comparison: greater than or equal
5932
bool operator>=(const const_iterator& other) const
5934
return not operator<(other);
5938
const_iterator& operator+=(difference_type i)
5940
switch (m_object->m_type)
5942
case basic_json::value_t::object:
5944
throw std::domain_error("cannot use offsets with object iterators");
5947
case basic_json::value_t::array:
5949
m_it.array_iterator += i;
5955
m_it.primitive_iterator += i;
5963
/// subtract from iterator
5964
const_iterator& operator-=(difference_type i)
5966
return operator+=(-i);
5970
const_iterator operator+(difference_type i)
5972
auto result = *this;
5977
/// subtract from iterator
5978
const_iterator operator-(difference_type i)
5980
auto result = *this;
5985
/// return difference
5986
difference_type operator-(const const_iterator& other) const
5988
switch (m_object->m_type)
5990
case basic_json::value_t::object:
5992
throw std::domain_error("cannot use offsets with object iterators");
5995
case basic_json::value_t::array:
5997
return m_it.array_iterator - other.m_it.array_iterator;
6002
return m_it.primitive_iterator - other.m_it.primitive_iterator;
6007
/// access to successor
6008
reference operator[](difference_type n) const
6010
switch (m_object->m_type)
6012
case basic_json::value_t::object:
6014
throw std::domain_error("cannot use operator[] for object iterators");
6017
case basic_json::value_t::array:
6019
return *(m_it.array_iterator + n);
6022
case basic_json::value_t::null:
6024
throw std::out_of_range("cannot get value");
6029
if (m_it.primitive_iterator == -n)
6035
throw std::out_of_range("cannot get value");
6041
/// return the key of an object iterator
6042
typename object_t::key_type key() const
6044
if (m_object->is_object())
6046
return m_it.object_iterator->first;
6050
throw std::domain_error("cannot use key() for non-object iterators");
6054
/// return the value of an iterator
6055
reference value() const
6061
/// associated JSON instance
6062
pointer m_object = nullptr;
6063
/// the actual iterator of the associated instance
6064
internal_iterator m_it = internal_iterator();
6068
@brief a mutable random access iterator for the @ref basic_json class
6070
@requirement The class satisfies the following concept requirements:
6071
- [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
6072
The iterator that can be moved to point (forward and backward) to any
6073
element in constant time.
6074
- [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
6075
It is possible to write to the pointed-to element.
6077
@since version 1.0.0
6079
class iterator : public const_iterator
6082
using base_iterator = const_iterator;
6083
using pointer = typename basic_json::pointer;
6084
using reference = typename basic_json::reference;
6086
/// default constructor
6087
iterator() = default;
6089
/// constructor for a given JSON instance
6090
iterator(pointer object) noexcept
6091
: base_iterator(object)
6094
/// copy constructor
6095
iterator(const iterator& other) noexcept
6096
: base_iterator(other)
6100
iterator& operator=(iterator other) noexcept(
6101
std::is_nothrow_move_constructible<pointer>::value and
6102
std::is_nothrow_move_assignable<pointer>::value and
6103
std::is_nothrow_move_constructible<internal_iterator>::value and
6104
std::is_nothrow_move_assignable<internal_iterator>::value
6107
base_iterator::operator=(other);
6111
/// return a reference to the value pointed to by the iterator
6112
reference operator*()
6114
return const_cast<reference>(base_iterator::operator*());
6117
/// dereference the iterator
6118
pointer operator->()
6120
return const_cast<pointer>(base_iterator::operator->());
6123
/// post-increment (it++)
6124
iterator operator++(int)
6126
iterator result = *this;
6127
base_iterator::operator++();
6131
/// pre-increment (++it)
6132
iterator& operator++()
6134
base_iterator::operator++();
6138
/// post-decrement (it--)
6139
iterator operator--(int)
6141
iterator result = *this;
6142
base_iterator::operator--();
6146
/// pre-decrement (--it)
6147
iterator& operator--()
6149
base_iterator::operator--();
6154
iterator& operator+=(difference_type i)
6156
base_iterator::operator+=(i);
6160
/// subtract from iterator
6161
iterator& operator-=(difference_type i)
6163
base_iterator::operator-=(i);
6168
iterator operator+(difference_type i)
6170
auto result = *this;
6175
/// subtract from iterator
6176
iterator operator-(difference_type i)
6178
auto result = *this;
6183
difference_type operator-(const iterator& other) const
6185
return base_iterator::operator-(other);
6188
/// access to successor
6189
reference operator[](difference_type n) const
6191
return const_cast<reference>(base_iterator::operator[](n));
6194
/// return the value of an iterator
6195
reference value() const
6197
return const_cast<reference>(base_iterator::value());
6202
@brief a template for a reverse iterator class
6204
@tparam Base the base iterator type to reverse. Valid types are @ref
6205
iterator (to create @ref reverse_iterator) and @ref const_iterator (to
6206
create @ref const_reverse_iterator).
6208
@requirement The class satisfies the following concept requirements:
6209
- [RandomAccessIterator](http://en.cppreference.com/w/cpp/concept/RandomAccessIterator):
6210
The iterator that can be moved to point (forward and backward) to any
6211
element in constant time.
6212
- [OutputIterator](http://en.cppreference.com/w/cpp/concept/OutputIterator):
6213
It is possible to write to the pointed-to element (only if @a Base is
6216
@since version 1.0.0
6218
template<typename Base>
6219
class json_reverse_iterator : public std::reverse_iterator<Base>
6222
/// shortcut to the reverse iterator adaptor
6223
using base_iterator = std::reverse_iterator<Base>;
6224
/// the reference type for the pointed-to element
6225
using reference = typename Base::reference;
6227
/// create reverse iterator from iterator
6228
json_reverse_iterator(const typename base_iterator::iterator_type& it)
6232
/// create reverse iterator from base class
6233
json_reverse_iterator(const base_iterator& it)
6237
/// post-increment (it++)
6238
json_reverse_iterator operator++(int)
6240
return base_iterator::operator++(1);
6243
/// pre-increment (++it)
6244
json_reverse_iterator& operator++()
6246
base_iterator::operator++();
6250
/// post-decrement (it--)
6251
json_reverse_iterator operator--(int)
6253
return base_iterator::operator--(1);
6256
/// pre-decrement (--it)
6257
json_reverse_iterator& operator--()
6259
base_iterator::operator--();
6264
json_reverse_iterator& operator+=(difference_type i)
6266
base_iterator::operator+=(i);
6271
json_reverse_iterator operator+(difference_type i) const
6273
auto result = *this;
6278
/// subtract from iterator
6279
json_reverse_iterator operator-(difference_type i) const
6281
auto result = *this;
6286
/// return difference
6287
difference_type operator-(const json_reverse_iterator& other) const
6289
return this->base() - other.base();
6292
/// access to successor
6293
reference operator[](difference_type n) const
6295
return *(this->operator+(n));
6298
/// return the key of an object iterator
6299
typename object_t::key_type key() const
6301
auto it = --this->base();
6305
/// return the value of an iterator
6306
reference value() const
6308
auto it = --this->base();
6309
return it.operator * ();
6315
//////////////////////
6316
// lexer and parser //
6317
//////////////////////
6320
@brief lexical analysis
6322
This class organizes the lexical analysis during JSON deserialization. The
6323
core of it is a scanner generated by re2c <http://re2c.org> that processes
6324
a buffer and recognizes tokens according to RFC 7159.
6329
/// token types for the parser
6330
enum class token_type
6332
uninitialized, ///< indicating the scanner is uninitialized
6333
literal_true, ///< the "true" literal
6334
literal_false, ///< the "false" literal
6335
literal_null, ///< the "null" literal
6336
value_string, ///< a string -- use get_string() for actual value
6337
value_number, ///< a number -- use get_number() for actual value
6338
begin_array, ///< the character for array begin "["
6339
begin_object, ///< the character for object begin "{"
6340
end_array, ///< the character for array end "]"
6341
end_object, ///< the character for object end "}"
6342
name_separator, ///< the name separator ":"
6343
value_separator, ///< the value separator ","
6344
parse_error, ///< indicating a parse error
6345
end_of_input ///< indicating the end of the input buffer
6348
/// the char type to use in the lexer
6349
using lexer_char_t = unsigned char;
6351
/// constructor with a given buffer
6352
explicit lexer(const string_t& s) noexcept
6353
: m_stream(nullptr), m_buffer(s)
6355
m_content = reinterpret_cast<const lexer_char_t*>(s.c_str());
6356
m_start = m_cursor = m_content;
6357
m_limit = m_content + s.size();
6360
/// constructor with a given stream
6361
explicit lexer(std::istream* s) noexcept
6362
: m_stream(s), m_buffer()
6364
getline(*m_stream, m_buffer);
6365
m_content = reinterpret_cast<const lexer_char_t*>(m_buffer.c_str());
6366
m_start = m_cursor = m_content;
6367
m_limit = m_content + m_buffer.size();
6370
/// default constructor
6373
// switch off unwanted functions
6374
lexer(const lexer&) = delete;
6375
lexer operator=(const lexer&) = delete;
6378
@brief create a string from a Unicode code point
6380
@param[in] codepoint1 the code point (can be high surrogate)
6381
@param[in] codepoint2 the code point (can be low surrogate or 0)
6383
@return string representation of the code point
6385
@throw std::out_of_range if code point is >0x10ffff; example: `"code
6386
points above 0x10FFFF are invalid"`
6387
@throw std::invalid_argument if the low surrogate is invalid; example:
6388
`""missing or wrong low surrogate""`
6390
@see <http://en.wikipedia.org/wiki/UTF-8#Sample_code>
6392
static string_t to_unicode(const std::size_t codepoint1,
6393
const std::size_t codepoint2 = 0)
6397
// calculate the codepoint from the given code points
6398
std::size_t codepoint = codepoint1;
6400
// check if codepoint1 is a high surrogate
6401
if (codepoint1 >= 0xD800 and codepoint1 <= 0xDBFF)
6403
// check if codepoint2 is a low surrogate
6404
if (codepoint2 >= 0xDC00 and codepoint2 <= 0xDFFF)
6407
// high surrogate occupies the most significant 22 bits
6409
// low surrogate occupies the least significant 15 bits
6411
// there is still the 0xD800, 0xDC00 and 0x10000 noise
6412
// in the result so we have to substract with:
6413
// (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00
6418
throw std::invalid_argument("missing or wrong low surrogate");
6422
if (codepoint < 0x80)
6424
// 1-byte characters: 0xxxxxxx (ASCII)
6425
result.append(1, static_cast<typename string_t::value_type>(codepoint));
6427
else if (codepoint <= 0x7ff)
6429
// 2-byte characters: 110xxxxx 10xxxxxx
6430
result.append(1, static_cast<typename string_t::value_type>(0xC0 | ((codepoint >> 6) & 0x1F)));
6431
result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
6433
else if (codepoint <= 0xffff)
6435
// 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx
6436
result.append(1, static_cast<typename string_t::value_type>(0xE0 | ((codepoint >> 12) & 0x0F)));
6437
result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F)));
6438
result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
6440
else if (codepoint <= 0x10ffff)
6442
// 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
6443
result.append(1, static_cast<typename string_t::value_type>(0xF0 | ((codepoint >> 18) & 0x07)));
6444
result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 12) & 0x3F)));
6445
result.append(1, static_cast<typename string_t::value_type>(0x80 | ((codepoint >> 6) & 0x3F)));
6446
result.append(1, static_cast<typename string_t::value_type>(0x80 | (codepoint & 0x3F)));
6450
throw std::out_of_range("code points above 0x10FFFF are invalid");
6456
/// return name of values of type token_type (only used for errors)
6457
static std::string token_type_name(token_type t)
6461
case token_type::uninitialized:
6462
return "<uninitialized>";
6463
case token_type::literal_true:
6464
return "true literal";
6465
case token_type::literal_false:
6466
return "false literal";
6467
case token_type::literal_null:
6468
return "null literal";
6469
case token_type::value_string:
6470
return "string literal";
6471
case token_type::value_number:
6472
return "number literal";
6473
case token_type::begin_array:
6475
case token_type::begin_object:
6477
case token_type::end_array:
6479
case token_type::end_object:
6481
case token_type::name_separator:
6483
case token_type::value_separator:
6485
case token_type::parse_error:
6486
return "<parse error>";
6487
case token_type::end_of_input:
6488
return "end of input";
6491
// catch non-enum values
6492
return "unknown token"; // LCOV_EXCL_LINE
6498
This function implements a scanner for JSON. It is specified using
6499
regular expressions that try to follow RFC 7159 as close as possible.
6500
These regular expressions are then translated into a deterministic
6501
finite automaton (DFA) by the tool re2c <http://re2c.org>. As a result,
6502
the translated code for this function consists of a large block of code
6505
@return the class of the next token read from the buffer
6507
token_type scan() noexcept
6509
// pointer for backtracking information
6512
// remember the begin of the token
6518
unsigned int yyaccept = 0;
6519
static const unsigned char yybm[] =
6521
0, 0, 0, 0, 0, 0, 0, 0,
6522
0, 32, 32, 0, 0, 32, 0, 0,
6523
64, 64, 64, 64, 64, 64, 64, 64,
6524
64, 64, 64, 64, 64, 64, 64, 64,
6525
96, 64, 0, 64, 64, 64, 64, 64,
6526
64, 64, 64, 64, 64, 64, 64, 64,
6527
192, 192, 192, 192, 192, 192, 192, 192,
6528
192, 192, 64, 64, 64, 64, 64, 64,
6529
64, 64, 64, 64, 64, 64, 64, 64,
6530
64, 64, 64, 64, 64, 64, 64, 64,
6531
64, 64, 64, 64, 64, 64, 64, 64,
6532
64, 64, 64, 64, 0, 64, 64, 64,
6533
64, 64, 64, 64, 64, 64, 64, 64,
6534
64, 64, 64, 64, 64, 64, 64, 64,
6535
64, 64, 64, 64, 64, 64, 64, 64,
6536
64, 64, 64, 64, 64, 64, 64, 64,
6537
64, 64, 64, 64, 64, 64, 64, 64,
6538
64, 64, 64, 64, 64, 64, 64, 64,
6539
64, 64, 64, 64, 64, 64, 64, 64,
6540
64, 64, 64, 64, 64, 64, 64, 64,
6541
64, 64, 64, 64, 64, 64, 64, 64,
6542
64, 64, 64, 64, 64, 64, 64, 64,
6543
64, 64, 64, 64, 64, 64, 64, 64,
6544
64, 64, 64, 64, 64, 64, 64, 64,
6545
64, 64, 64, 64, 64, 64, 64, 64,
6546
64, 64, 64, 64, 64, 64, 64, 64,
6547
64, 64, 64, 64, 64, 64, 64, 64,
6548
64, 64, 64, 64, 64, 64, 64, 64,
6549
64, 64, 64, 64, 64, 64, 64, 64,
6550
64, 64, 64, 64, 64, 64, 64, 64,
6551
64, 64, 64, 64, 64, 64, 64, 64,
6552
64, 64, 64, 64, 64, 64, 64, 64,
6554
if ((m_limit - m_cursor) < 5)
6556
yyfill(); // LCOV_EXCL_LINE;
6567
goto basic_json_parser_28;
6571
goto basic_json_parser_30;
6575
goto basic_json_parser_4;
6582
goto basic_json_parser_2;
6586
goto basic_json_parser_30;
6596
goto basic_json_parser_27;
6600
goto basic_json_parser_30;
6602
goto basic_json_parser_16;
6610
goto basic_json_parser_23;
6612
goto basic_json_parser_30;
6618
goto basic_json_parser_24;
6622
goto basic_json_parser_26;
6624
goto basic_json_parser_18;
6637
goto basic_json_parser_8;
6641
goto basic_json_parser_30;
6643
goto basic_json_parser_10;
6649
goto basic_json_parser_22;
6653
goto basic_json_parser_30;
6655
goto basic_json_parser_20;
6664
goto basic_json_parser_21;
6668
goto basic_json_parser_30;
6670
goto basic_json_parser_12;
6678
goto basic_json_parser_30;
6680
goto basic_json_parser_14;
6686
goto basic_json_parser_6;
6688
goto basic_json_parser_30;
6693
basic_json_parser_2:
6696
goto basic_json_parser_5;
6697
basic_json_parser_3:
6701
basic_json_parser_4:
6703
if (m_limit <= m_cursor)
6705
yyfill(); // LCOV_EXCL_LINE;
6708
basic_json_parser_5:
6709
if (yybm[0 + yych] & 32)
6711
goto basic_json_parser_4;
6713
goto basic_json_parser_3;
6714
basic_json_parser_6:
6716
yych = *(m_marker = ++m_cursor);
6719
goto basic_json_parser_64;
6721
basic_json_parser_7:
6723
return token_type::parse_error;
6725
basic_json_parser_8:
6728
return token_type::begin_array;
6730
basic_json_parser_10:
6733
return token_type::end_array;
6735
basic_json_parser_12:
6738
return token_type::begin_object;
6740
basic_json_parser_14:
6743
return token_type::end_object;
6745
basic_json_parser_16:
6748
return token_type::value_separator;
6750
basic_json_parser_18:
6753
return token_type::name_separator;
6755
basic_json_parser_20:
6757
yych = *(m_marker = ++m_cursor);
6760
goto basic_json_parser_60;
6762
goto basic_json_parser_7;
6763
basic_json_parser_21:
6765
yych = *(m_marker = ++m_cursor);
6768
goto basic_json_parser_56;
6770
goto basic_json_parser_7;
6771
basic_json_parser_22:
6773
yych = *(m_marker = ++m_cursor);
6776
goto basic_json_parser_51;
6778
goto basic_json_parser_7;
6779
basic_json_parser_23:
6783
goto basic_json_parser_7;
6787
goto basic_json_parser_50;
6791
goto basic_json_parser_41;
6793
goto basic_json_parser_7;
6794
basic_json_parser_24:
6796
yych = *(m_marker = ++m_cursor);
6801
goto basic_json_parser_43;
6808
goto basic_json_parser_44;
6812
goto basic_json_parser_44;
6815
basic_json_parser_25:
6817
return token_type::value_number;
6819
basic_json_parser_26:
6821
yych = *(m_marker = ++m_cursor);
6822
goto basic_json_parser_42;
6823
basic_json_parser_27:
6825
yych = *(m_marker = ++m_cursor);
6828
goto basic_json_parser_7;
6830
goto basic_json_parser_32;
6831
basic_json_parser_28:
6834
return token_type::end_of_input;
6836
basic_json_parser_30:
6838
goto basic_json_parser_7;
6839
basic_json_parser_31:
6841
if (m_limit <= m_cursor)
6843
yyfill(); // LCOV_EXCL_LINE;
6846
basic_json_parser_32:
6847
if (yybm[0 + yych] & 64)
6849
goto basic_json_parser_31;
6853
goto basic_json_parser_33;
6857
goto basic_json_parser_35;
6859
goto basic_json_parser_34;
6860
basic_json_parser_33:
6861
m_cursor = m_marker;
6864
goto basic_json_parser_7;
6868
goto basic_json_parser_25;
6870
basic_json_parser_34:
6872
if (m_limit <= m_cursor)
6874
yyfill(); // LCOV_EXCL_LINE;
6883
goto basic_json_parser_31;
6887
goto basic_json_parser_33;
6889
goto basic_json_parser_31;
6897
goto basic_json_parser_33;
6899
goto basic_json_parser_31;
6905
goto basic_json_parser_31;
6907
goto basic_json_parser_33;
6917
goto basic_json_parser_31;
6921
goto basic_json_parser_31;
6923
goto basic_json_parser_33;
6931
goto basic_json_parser_31;
6933
goto basic_json_parser_33;
6939
goto basic_json_parser_31;
6943
goto basic_json_parser_37;
6945
goto basic_json_parser_33;
6949
basic_json_parser_35:
6952
return token_type::value_string;
6954
basic_json_parser_37:
6956
if (m_limit <= m_cursor)
6958
yyfill(); // LCOV_EXCL_LINE;
6965
goto basic_json_parser_33;
6969
goto basic_json_parser_33;
6976
goto basic_json_parser_38;
6980
goto basic_json_parser_33;
6984
goto basic_json_parser_33;
6987
basic_json_parser_38:
6989
if (m_limit <= m_cursor)
6991
yyfill(); // LCOV_EXCL_LINE;
6998
goto basic_json_parser_33;
7002
goto basic_json_parser_33;
7009
goto basic_json_parser_39;
7013
goto basic_json_parser_33;
7017
goto basic_json_parser_33;
7020
basic_json_parser_39:
7022
if (m_limit <= m_cursor)
7024
yyfill(); // LCOV_EXCL_LINE;
7031
goto basic_json_parser_33;
7035
goto basic_json_parser_33;
7042
goto basic_json_parser_40;
7046
goto basic_json_parser_33;
7050
goto basic_json_parser_33;
7053
basic_json_parser_40:
7055
if (m_limit <= m_cursor)
7057
yyfill(); // LCOV_EXCL_LINE;
7064
goto basic_json_parser_33;
7068
goto basic_json_parser_31;
7070
goto basic_json_parser_33;
7076
goto basic_json_parser_31;
7080
goto basic_json_parser_33;
7084
goto basic_json_parser_31;
7086
goto basic_json_parser_33;
7088
basic_json_parser_41:
7090
m_marker = ++m_cursor;
7091
if ((m_limit - m_cursor) < 3)
7093
yyfill(); // LCOV_EXCL_LINE;
7096
basic_json_parser_42:
7097
if (yybm[0 + yych] & 128)
7099
goto basic_json_parser_41;
7105
goto basic_json_parser_25;
7112
goto basic_json_parser_44;
7116
goto basic_json_parser_44;
7118
goto basic_json_parser_25;
7120
basic_json_parser_43:
7124
goto basic_json_parser_33;
7128
goto basic_json_parser_48;
7130
goto basic_json_parser_33;
7131
basic_json_parser_44:
7137
goto basic_json_parser_33;
7144
goto basic_json_parser_45;
7148
goto basic_json_parser_33;
7152
goto basic_json_parser_46;
7154
goto basic_json_parser_33;
7156
basic_json_parser_45:
7160
goto basic_json_parser_33;
7164
goto basic_json_parser_33;
7166
basic_json_parser_46:
7168
if (m_limit <= m_cursor)
7170
yyfill(); // LCOV_EXCL_LINE;
7175
goto basic_json_parser_25;
7179
goto basic_json_parser_46;
7181
goto basic_json_parser_25;
7182
basic_json_parser_48:
7184
m_marker = ++m_cursor;
7185
if ((m_limit - m_cursor) < 3)
7187
yyfill(); // LCOV_EXCL_LINE;
7194
goto basic_json_parser_25;
7198
goto basic_json_parser_48;
7200
goto basic_json_parser_25;
7206
goto basic_json_parser_44;
7210
goto basic_json_parser_44;
7212
goto basic_json_parser_25;
7214
basic_json_parser_50:
7216
yych = *(m_marker = ++m_cursor);
7221
goto basic_json_parser_43;
7223
goto basic_json_parser_25;
7229
goto basic_json_parser_44;
7233
goto basic_json_parser_44;
7235
goto basic_json_parser_25;
7237
basic_json_parser_51:
7241
goto basic_json_parser_33;
7246
goto basic_json_parser_33;
7251
goto basic_json_parser_33;
7255
return token_type::literal_false;
7257
basic_json_parser_56:
7261
goto basic_json_parser_33;
7266
goto basic_json_parser_33;
7270
return token_type::literal_true;
7272
basic_json_parser_60:
7276
goto basic_json_parser_33;
7281
goto basic_json_parser_33;
7285
return token_type::literal_null;
7287
basic_json_parser_64:
7291
goto basic_json_parser_33;
7302
/// append data from the stream to the internal buffer
7303
void yyfill() noexcept
7305
if (not m_stream or not * m_stream)
7310
const ssize_t offset_start = m_start - m_content;
7311
const ssize_t offset_marker = m_marker - m_start;
7312
const ssize_t offset_cursor = m_cursor - m_start;
7314
m_buffer.erase(0, static_cast<size_t>(offset_start));
7316
std::getline(*m_stream, line);
7317
m_buffer += "\n" + line; // add line with newline symbol
7319
m_content = reinterpret_cast<const lexer_char_t*>(m_buffer.c_str());
7320
m_start = m_content;
7321
m_marker = m_start + offset_marker;
7322
m_cursor = m_start + offset_cursor;
7323
m_limit = m_start + m_buffer.size() - 1;
7326
/// return string representation of last read token
7327
string_t get_token() const noexcept
7329
return string_t(reinterpret_cast<typename string_t::const_pointer>(m_start),
7330
static_cast<size_t>(m_cursor - m_start));
7334
@brief return string value for string tokens
7336
The function iterates the characters between the opening and closing
7337
quotes of the string value. The complete string is the range
7338
[m_start,m_cursor). Consequently, we iterate from m_start+1 to
7341
We differentiate two cases:
7343
1. Escaped characters. In this case, a new character is constructed
7344
according to the nature of the escape. Some escapes create new
7345
characters (e.g., @c "\\n" is replaced by @c "\n"), some are copied
7346
as is (e.g., @c "\\\\"). Furthermore, Unicode escapes of the shape
7347
@c "\\uxxxx" need special care. In this case, to_unicode takes care
7348
of the construction of the values.
7349
2. Unescaped characters are copied as is.
7351
@return string value of current token without opening and closing quotes
7352
@throw std::out_of_range if to_unicode fails
7354
string_t get_string() const
7357
result.reserve(static_cast<size_t>(m_cursor - m_start - 2));
7359
// iterate the result between the quotes
7360
for (const lexer_char_t* i = m_start + 1; i < m_cursor - 1; ++i)
7362
// process escaped characters
7365
// read next character
7370
// the default escapes
7415
// get code xxxx from uxxxx
7416
auto codepoint = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>(i + 1),
7417
4).c_str(), nullptr, 16);
7419
// check if codepoint is a high surrogate
7420
if (codepoint >= 0xD800 and codepoint <= 0xDBFF)
7422
// make sure there is a subsequent unicode
7423
if ((i + 6 >= m_limit) or * (i + 5) != '\\' or * (i + 6) != 'u')
7425
throw std::invalid_argument("missing low surrogate");
7428
// get code yyyy from uxxxx\uyyyy
7429
auto codepoint2 = std::strtoul(std::string(reinterpret_cast<typename string_t::const_pointer>
7430
(i + 7), 4).c_str(), nullptr, 16);
7431
result += to_unicode(codepoint, codepoint2);
7432
// skip the next 10 characters (xxxx\uyyyy)
7437
// add unicode character(s)
7438
result += to_unicode(codepoint);
7439
// skip the next four characters (xxxx)
7448
// all other characters are just copied to the end of the
7450
result.append(1, static_cast<typename string_t::value_type>(*i));
7458
@brief return number value for number tokens
7460
This function translates the last token into a floating point number.
7461
The pointer m_start points to the beginning of the parsed number. We
7462
pass this pointer to std::strtod which sets endptr to the first
7463
character past the converted number. If this pointer is not the same as
7464
m_cursor, then either more or less characters have been used during the
7465
comparison. This can happen for inputs like "01" which will be treated
7466
like number 0 followed by number 1.
7468
@return the result of the number conversion or NAN if the conversion
7469
read past the current token. The latter case needs to be treated by the
7472
@throw std::range_error if passed value is out of range
7474
long double get_number() const
7477
typename string_t::value_type* endptr;
7478
const auto float_val = std::strtold(reinterpret_cast<typename string_t::const_pointer>(m_start),
7481
// return float_val if the whole number was translated and NAN
7483
return (reinterpret_cast<lexer_char_t*>(endptr) == m_cursor) ? float_val : NAN;
7487
/// optional input stream
7488
std::istream* m_stream;
7491
/// the buffer pointer
7492
const lexer_char_t* m_content = nullptr;
7493
/// pointer to the beginning of the current symbol
7494
const lexer_char_t* m_start = nullptr;
7495
/// pointer for backtracking information
7496
const lexer_char_t* m_marker = nullptr;
7497
/// pointer to the current symbol
7498
const lexer_char_t* m_cursor = nullptr;
7499
/// pointer to the end of the buffer
7500
const lexer_char_t* m_limit = nullptr;
7504
@brief syntax analysis
7506
This class implements a recursive decent parser.
7511
/// constructor for strings
7512
parser(const string_t& s, parser_callback_t cb = nullptr)
7513
: callback(cb), m_lexer(s)
7519
/// a parser reading from an input stream
7520
parser(std::istream& _is, parser_callback_t cb = nullptr)
7521
: callback(cb), m_lexer(&_is)
7527
/// public parser interface
7530
basic_json result = parse_internal(true);
7532
expect(lexer::token_type::end_of_input);
7534
// return parser result and replace it with null in case the
7535
// top-level value was discarded by the callback function
7536
return result.is_discarded() ? basic_json() : result;
7540
/// the actual parser
7541
basic_json parse_internal(bool keep)
7543
auto result = basic_json(value_t::discarded);
7547
case lexer::token_type::begin_object:
7549
if (keep and (not callback or (keep = callback(depth++, parse_event_t::object_start, result))))
7551
// explicitly set result to object to cope with {}
7552
result.m_type = value_t::object;
7553
result.m_value = json_value(value_t::object);
7559
// closing } -> we are done
7560
if (last_token == lexer::token_type::end_object)
7563
if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
7565
result = basic_json(value_t::discarded);
7570
// no comma is expected here
7571
unexpect(lexer::token_type::value_separator);
7573
// otherwise: parse key-value pairs
7576
// ugly, but could be fixed with loop reorganization
7577
if (last_token == lexer::token_type::value_separator)
7583
expect(lexer::token_type::value_string);
7584
const auto key = m_lexer.get_string();
7586
bool keep_tag = false;
7592
keep_tag = callback(depth, parse_event_t::key, k);
7600
// parse separator (:)
7602
expect(lexer::token_type::name_separator);
7604
// parse and add value
7606
auto value = parse_internal(keep);
7607
if (keep and keep_tag and not value.is_discarded())
7609
result[key] = std::move(value);
7612
while (last_token == lexer::token_type::value_separator);
7615
expect(lexer::token_type::end_object);
7617
if (keep and callback and not callback(--depth, parse_event_t::object_end, result))
7619
result = basic_json(value_t::discarded);
7625
case lexer::token_type::begin_array:
7627
if (keep and (not callback or (keep = callback(depth++, parse_event_t::array_start, result))))
7629
// explicitly set result to object to cope with []
7630
result.m_type = value_t::array;
7631
result.m_value = json_value(value_t::array);
7637
// closing ] -> we are done
7638
if (last_token == lexer::token_type::end_array)
7641
if (callback and not callback(--depth, parse_event_t::array_end, result))
7643
result = basic_json(value_t::discarded);
7648
// no comma is expected here
7649
unexpect(lexer::token_type::value_separator);
7651
// otherwise: parse values
7654
// ugly, but could be fixed with loop reorganization
7655
if (last_token == lexer::token_type::value_separator)
7661
auto value = parse_internal(keep);
7662
if (keep and not value.is_discarded())
7664
result.push_back(std::move(value));
7667
while (last_token == lexer::token_type::value_separator);
7670
expect(lexer::token_type::end_array);
7672
if (keep and callback and not callback(--depth, parse_event_t::array_end, result))
7674
result = basic_json(value_t::discarded);
7680
case lexer::token_type::literal_null:
7683
result.m_type = value_t::null;
7687
case lexer::token_type::value_string:
7689
const auto s = m_lexer.get_string();
7691
result = basic_json(s);
7695
case lexer::token_type::literal_true:
7698
result.m_type = value_t::boolean;
7699
result.m_value = true;
7703
case lexer::token_type::literal_false:
7706
result.m_type = value_t::boolean;
7707
result.m_value = false;
7711
case lexer::token_type::value_number:
7713
auto float_val = m_lexer.get_number();
7715
// NAN is returned if token could not be translated
7717
if (std::isnan(float_val))
7719
throw std::invalid_argument(std::string("parse error - ") +
7720
m_lexer.get_token() + " is not a number");
7725
// check if conversion loses precision
7726
const auto int_val = static_cast<number_integer_t>(float_val);
7727
if (approx(float_val, static_cast<long double>(int_val)))
7729
// we would not lose precision -> return int
7730
result.m_type = value_t::number_integer;
7731
result.m_value = int_val;
7735
// we would lose precision -> return float
7736
result.m_type = value_t::number_float;
7737
result.m_value = static_cast<number_float_t>(float_val);
7744
// the last token was unexpected
7745
unexpect(last_token);
7749
if (keep and callback and not callback(depth, parse_event_t::value, result))
7751
result = basic_json(value_t::discarded);
7756
/// get next token from lexer
7757
typename lexer::token_type get_token()
7759
last_token = m_lexer.scan();
7763
void expect(typename lexer::token_type t) const
7765
if (t != last_token)
7767
std::string error_msg = "parse error - unexpected ";
7768
error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token() + "'") :
7769
lexer::token_type_name(last_token));
7770
error_msg += "; expected " + lexer::token_type_name(t);
7771
throw std::invalid_argument(error_msg);
7775
void unexpect(typename lexer::token_type t) const
7777
if (t == last_token)
7779
std::string error_msg = "parse error - unexpected ";
7780
error_msg += (last_token == lexer::token_type::parse_error ? ("'" + m_lexer.get_token() + "'") :
7781
lexer::token_type_name(last_token));
7782
throw std::invalid_argument(error_msg);
7787
/// current level of recursion
7789
/// callback function
7790
parser_callback_t callback;
7791
/// the type of the last read token
7792
typename lexer::token_type last_token = lexer::token_type::uninitialized;
7804
@brief default JSON class
7806
This type is the default specialization of the @ref basic_json class which uses
7807
the standard template types.
7809
@since version 1.0.0
7811
using json = basic_json<>;
7815
/////////////////////////
7816
// nonmember functions //
7817
/////////////////////////
7819
// specialization of std::swap, and std::hash
7823
@brief exchanges the values of two JSON objects
7825
@since version 1.0.0
7828
inline void swap(nlohmann::json& j1,
7829
nlohmann::json& j2) noexcept(
7830
is_nothrow_move_constructible<nlohmann::json>::value and
7831
is_nothrow_move_assignable<nlohmann::json>::value
7837
/// hash value for JSON objects
7839
struct hash<nlohmann::json>
7842
@brief return a hash value for a JSON object
7844
@since version 1.0.0
7846
std::size_t operator()(const nlohmann::json& j) const
7848
// a naive hashing via the string representation
7849
const auto& h = hash<nlohmann::json::string_t>();
7856
@brief user-defined string literal for JSON values
7858
This operator implements a user-defined string literal for JSON objects. It can
7859
be used by adding \p "_json" to a string literal and returns a JSON object if
7860
no parse error occurred.
7862
@param[in] s a string representation of a JSON object
7863
@return a JSON object
7865
@since version 1.0.0
7867
inline nlohmann::json operator "" _json(const char* s, std::size_t)
7869
return nlohmann::json::parse(reinterpret_cast<nlohmann::json::string_t::value_type*>
7870
(const_cast<char*>(s)));