• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# basic_json::basic_json
2
3```cpp
4// 1
5basic_json(const value_t v);
6
7// 2
8basic_json(std::nullptr_t = nullptr) noexcept;
9
10// 3
11template<typename CompatibleType>
12basic_json(CompatibleType&& val) noexcept(noexcept(
13           JSONSerializer<U>::to_json(std::declval<basic_json_t&>(),
14                                      std::forward<CompatibleType>(val))));
15
16// 4
17template<typename BasicJsonType>
18basic_json(const BasicJsonType& val);
19
20// 5
21basic_json(initializer_list_t init,
22           bool type_deduction = true,
23           value_t manual_type = value_t::array);
24
25// 6
26basic_json(size_type cnt, const basic_json& val);
27
28// 7
29basic_json(iterator first, iterator last);
30basic_json(const_iterator first, const_iterator last);
31
32// 8
33basic_json(const basic_json& other);
34
35// 9
36basic_json(basic_json&& other) noexcept;
37```
38
391. Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends
40   on the type:
41
42    Value type  | initial value
43    ----------- | -------------
44    null        | `#!json null`
45    boolean     | `#!json false`
46    string      | `#!json ""`
47    number      | `#!json 0`
48    object      | `#!json {}`
49    array       | `#!json []`
50    binary      | empty array
51
522. Create a `#!json null` JSON value. It either takes a null pointer as parameter (explicitly creating `#!json null`)
53   or no parameter (implicitly creating `#!json null`). The passed null pointer itself is not read -- it is only used to
54   choose the right constructor.
55
563. This is a "catch all" constructor for all compatible JSON types; that is, types for which a `to_json()` method
57   exists. The constructor forwards the parameter `val` to that method (to `json_serializer<U>::to_json` method with
58   `U = uncvref_t<CompatibleType>`, to be exact).
59
60    Template type `CompatibleType` includes, but is not limited to, the following types:
61
62    - **arrays**: [`array_t`](array_t.md) and all kinds of compatible containers such as `std::vector`, `std::deque`,
63     `std::list`, `std::forward_list`, `std::array`, `std::valarray`, `std::set`, `std::unordered_set`, `std::multiset`,
64     and `std::unordered_multiset` with a `value_type` from which a `basic_json` value can be constructed.
65    - **objects**: [`object_t`](object_t.md) and all kinds of compatible associative containers such as `std::map`,
66     `std::unordered_map`, `std::multimap`, and `std::unordered_multimap` with a `key_type` compatible to `string_t`
67     and a `value_type` from which a `basic_json` value can be constructed.
68    - **strings**: `string_t`, string literals, and all compatible string containers can be used.
69    - **numbers**: [`number_integer_t`](number_integer_t.md), [`number_unsigned_t`](number_unsigned_t.md),
70     [`number_float_t`](number_float_t.md), and all convertible number types such as `int`, `size_t`, `int64_t`, `float`
71     or `double` can be used.
72    - **boolean**: `boolean_t` / `bool` can be used.
73    - **binary**: `binary_t` / `std::vector<uint8_t>` may be used; unfortunately because string literals cannot be
74     distinguished from binary character arrays by the C++ type system, all types compatible with `const char*` will be
75     directed to the string constructor instead. This is both for backwards compatibility, and due to the fact that a
76     binary type is not a standard JSON type.
77
78    See the examples below.
79
804. This is a constructor for existing `basic_json` types. It does not hijack copy/move constructors, since the parameter
81   has different template arguments than the current ones.
82
83    The constructor tries to convert the internal `m_value` of the parameter.
84
855. Creates a JSON value of type array or object from the passed initializer list `init`. In case `type_deduction` is
86   `#!cpp true` (default), the type of the JSON value to be created is deducted from the initializer list `init`
87   according to the following rules:
88
89    1. If the list is empty, an empty JSON object value `{}` is created.
90    2. If the list consists of pairs whose first element is a string, a JSON object value is created where the first
91      elements of the pairs are treated as keys and the second elements are as values.
92    3. In all other cases, an array is created.
93
94    The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows:
95
96    1. The empty initializer list is written as `#!cpp {}` which is exactly an empty JSON object.
97    2. C++ has no way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be
98       of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an
99       object.
100    3. In all other cases, the initializer list could not be interpreted as JSON object type, so interpreting it as JSON
101       array type is safe.
102
103    With the rules described above, the following JSON values cannot be expressed by an initializer list:
104
105    - the empty array (`#!json []`): use `array(initializer_list_t)` with an empty initializer list in this case
106    - arrays whose elements satisfy rule 2: use `array(initializer_list_t)` with the same initializer list in this case
107
1086. Constructs a JSON array value by creating `cnt` copies of a passed value. In case `cnt` is `0`, an empty array is
109   created.
110
1117. Constructs the JSON value with the contents of the range `[first, last)`. The semantics depends on the different
112   types a JSON value can have:
113
114    - In case of a `#!json null` type, [invalid_iterator.206](../../home/exceptions.md#jsonexceptioninvalid_iterator206)
115      is thrown.
116    - In case of other primitive types (number, boolean, or string), `first` must be `begin()` and `last` must be
117      `end()`. In this case, the value is copied. Otherwise,
118      [`invalid_iterator.204`](../../home/exceptions.md#jsonexceptioninvalid_iterator204) is thrown.
119    - In case of structured types (array, object), the constructor behaves as similar versions for `std::vector` or
120      `std::map`; that is, a JSON array or object is constructed from the values in the range.
121
1228. Creates a copy of a given JSON value.
123
1249. Move constructor. Constructs a JSON value with the contents of the given value `other` using move semantics. It
125   "steals" the resources from `other` and leaves it as JSON `#!json null` value.
126
127## Template parameters
128
129`CompatibleType`
130:   a type such that:
131
132    - `CompatibleType` is not derived from `std::istream`,
133    - `CompatibleType` is not `basic_json` (to avoid hijacking copy/move constructors),
134    - `CompatibleType` is not a different `basic_json` type (i.e. with different template arguments)
135    - `CompatibleType` is not a `basic_json` nested type (e.g., `json_pointer`, `iterator`, etc.)
136    - `json_serializer<U>` (with `U = uncvref_t<CompatibleType>`) has a `to_json(basic_json_t&, CompatibleType&&)`
137       method
138
139`BasicJsonType`:
140:   a type such that:
141
142    - `BasicJsonType` is a `basic_json` type.
143    - `BasicJsonType` has different template arguments than `basic_json_t`.
144
145## Parameters
146
147`v` (in)
148:   the type of the value to create
149
150`val` (in)
151:   the value to be forwarded to the respective constructor
152
153`init` (in)
154:   initializer list with JSON values
155
156`type_deduction` (in)
157:   internal parameter; when set to `#!cpp true`, the type of the JSON value is deducted from the initializer list
158    `init`; when set to `#!cpp false`, the type provided via `manual_type` is forced. This mode is used by the functions
159    `array(initializer_list_t)` and `object(initializer_list_t)`.
160
161`manual_type` (in)
162:   internal parameter; when `type_deduction` is set to `#!cpp false`, the created JSON value will use the provided type
163    (only `value_t::array` and `value_t::object` are valid); when `type_deduction` is set to `#!cpp true`, this
164    parameter has no effect
165
166`cnt` (in)
167:   the number of JSON copies of `val` to create
168
169`first` (in)
170:   begin of the range to copy from (included)
171
172`last` (in)
173:   end of the range to copy from (excluded)
174
175`other` (in)
176:   the JSON value to copy/move
177
178## Exceptions
179
1801. /
1812. The function does not throw exceptions.
1823. /
1834. /
1845. The function can throw the following exceptions:
185    - Throws [`type_error.301`](../../home/exceptions.md#jsonexceptiontype_error301) if `type_deduction` is
186      `#!cpp false`, `manual_type` is `value_t::object`, but `init` contains an element which is not a pair whose first
187      element is a string. In this case, the constructor could not create an object. If `type_deduction` would have been
188      `#!cpp true`, an array would have been created. See `object(initializer_list_t)` for an example.
1896. /
1907. The function can throw the following exceptions:
191    - Throws [`invalid_iterator.201`](../../home/exceptions.md#jsonexceptioninvalid_iterator201) if iterators `first`
192      and `last` are not compatible (i.e., do not belong to the same JSON value). In this case, the range
193      `[first, last)` is undefined.
194    - Throws [`invalid_iterator.204`](../../home/exceptions.md#jsonexceptioninvalid_iterator204) if iterators `first`
195      and `last` belong to a primitive type (number, boolean, or string), but `first` does not point to the first
196      element any more. In this case, the range `[first, last)` is undefined. See example code below.
197    - Throws [`invalid_iterator.206`](../../home/exceptions.md#jsonexceptioninvalid_iterator206) if iterators `first`
198      and `last` belong to a `#!json null` value. In this case, the range `[first, last)` is undefined.
1998. /
2009. The function does not throw exceptions.
201
202## Exception safety
203
2041. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
2052. No-throw guarantee: this constructor never throws exceptions.
2063. Depends on the called constructor. For types directly supported by the library (i.e., all types for which no
207   `to_json()` function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any
208   JSON value.
2094. Depends on the called constructor. For types directly supported by the library (i.e., all types for which no
210   `to_json()` function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any
211   JSON value.
2125. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
2136. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
2147. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
2158. Strong guarantee: if an exception is thrown, there are no changes to any JSON value.
2169. No-throw guarantee: this constructor never throws exceptions.
217
218## Complexity
219
2201. Constant.
2212. Constant.
2223. Usually linear in the size of the passed `val`, also depending on the implementation of the called `to_json()`
223   method.
2244. Usually linear in the size of the passed `val`, also depending on the implementation of the called `to_json()`
225   method.
2265. Linear in the size of the initializer list `init`.
2276. Linear in `cnt`.
2287. Linear in distance between `first` and `last`.
2298. Linear in the size of `other`.
2309. Constant.
231
232## Notes
233
234- Overload 5:
235
236    !!! note
237
238        When used without parentheses around an empty initializer list, `basic_json()` is called instead of this
239        function, yielding the JSON `#!json null` value.
240
241- Overload 7:
242
243    !!! info "Preconditions"
244
245        - Iterators `first` and `last` must be initialized. **This precondition is enforced with an assertion (see
246          warning).** If assertions are switched off, a violation of this precondition yields undefined behavior.
247        - Range `[first, last)` is valid. Usually, this precondition cannot be checked efficiently. Only certain edge
248          cases are detected; see the description of the exceptions above. A violation of this precondition yields
249          undefined behavior.
250
251    !!! warning
252
253        A precondition is enforced with a runtime assertion that will result in calling `std::abort` if this
254        precondition is not met. Assertions can be disabled by defining `NDEBUG` at compile time. See
255        <https://en.cppreference.com/w/cpp/error/assert> for more information.
256
257- Overload 8:
258
259    !!! info "Postcondition"
260
261        `#!cpp *this == other`
262
263- Overload 9:
264
265    !!! info "Postconditions"
266
267        - `#!cpp `*this` has the same value as `other` before the call.
268        - `other` is a JSON `#!json null` value
269
270## Example
271
272??? example
273
274    The following code shows the constructor for different `value_t` values.
275
276    ```cpp
277    --8<-- "examples/basic_json__value_t.cpp"
278    ```
279
280    Output:
281
282    ```json
283    --8<-- "examples/basic_json__value_t.output"
284    ```
285
286??? example
287
288    The following code shows the constructor with and without a null pointer parameter.
289
290    ```cpp
291    --8<-- "examples/basic_json__nullptr_t.cpp"
292    ```
293
294    Output:
295
296    ```json
297    --8<-- "examples/basic_json__nullptr_t.output"
298    ```
299
300??? example
301
302    The following code shows the constructor with several compatible types.
303
304    ```cpp
305    --8<-- "examples/basic_json__CompatibleType.cpp"
306    ```
307
308    Output:
309
310    ```json
311    --8<-- "examples/basic_json__CompatibleType.output"
312    ```
313
314??? example
315
316    The example below shows how JSON values are created from initializer lists.
317
318    ```cpp
319    --8<-- "examples/basic_json__list_init_t.cpp"
320    ```
321
322    Output:
323
324    ```json
325    --8<-- "examples/basic_json__list_init_t.output"
326    ```
327
328??? example
329
330    The following code shows examples for creating arrays with several copies of a given value.
331
332    ```cpp
333    --8<-- "examples/basic_json__size_type_basic_json.cpp"
334    ```
335
336    Output:
337
338    ```json
339    --8<-- "examples/basic_json__size_type_basic_json.output"
340    ```
341
342??? example
343
344    The example below shows several ways to create JSON values by specifying a subrange with iterators.
345
346    ```cpp
347    --8<-- "examples/basic_json__InputIt_InputIt.cpp"
348    ```
349
350    Output:
351
352    ```json
353    --8<-- "examples/basic_json__InputIt_InputIt.output"
354    ```
355
356??? example
357
358    The following code shows an example for the copy constructor.
359
360    ```cpp
361    --8<-- "examples/basic_json__basic_json.cpp"
362    ```
363
364    Output:
365
366    ```json
367    --8<-- "examples/basic_json__basic_json.output"
368    ```
369
370??? example
371
372    The code below shows the move constructor explicitly called via `std::move`.
373
374    ```cpp
375    --8<-- "examples/basic_json__moveconstructor.cpp"
376    ```
377
378    Output:
379
380    ```json
381    --8<-- "examples/basic_json__moveconstructor.output"
382    ```
383
384## Version history
385
3861. Since version 1.0.0.
3872. Since version 1.0.0.
3883. Since version 2.1.0.
3894. Since version 3.2.0.
3905. Since version 1.0.0.
3916. Since version 1.0.0.
3927. Since version 1.0.0.
3938. Since version 1.0.0.
3949. Since version 1.0.0.
395