File: basic_json_options.md

package info (click to toggle)
jsoncons 1.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 17,584 kB
  • sloc: cpp: 136,382; sh: 33; makefile: 5
file content (495 lines) | stat: -rw-r--r-- 16,212 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
### jsoncons::basic_json_options

```cpp
#include <jsoncons/json_options.hpp>

template< 
    typename CharT
> class basic_json_options;
```

<br>

![basic_json_options](./diagrams/basic_json_options.png)

Specifies options for reading and writing JSON text. 

Option|Reading|Writing|Default
------|-------|-------|-------
nan_to_str|Substitute string with `NaN`, if enabled|Sets a string replacement for `NaN` when writing JSON|Unenabled
inf_to_str|Substitute string with `infinity`, if enabled|Sets a string replacement for infinity when writing JSON|Unenabled
neginf_to_str|Substitute string with `negative infinity`, if enabled|Sets a string replacement for negative infinity when writing JSON|Unenabled
nan_to_num| |Sets a number replacement for `NaN` when writing JSON|Unenabled
inf_to_num| |Sets a number replacement for `Infinity` when writing JSON|Unenabled
neginf_to_num| |Sets a number replacement for `Negative Infinity` when writing JSON|Unenabled
max_nesting_depth|Maximum nesting depth allowed when parsing JSON|Maximum nesting depth allowed when serializing JSON|1024
lossless_number|If `true`, parse numbers with exponents and fractional parts as strings with semantic tagging `semantic_tag::bigdec`.| |`false`
allow_comments (since 1.3.0)|If 'true', allow (and ignore) comments when parsing JSON| |`true`
allow_trailing_comma (since 1.3.0)|If 'true', an extra comma at the end of a list of JSON values in an object or array is allowed (and ignored)| |false
err_handler (since 0.171.0)|Defines an [error handler](err_handler.md) for parsing JSON.| |`default_json_parsing`
indent_size| |The indent size|4
spaces_around_colon| |Indicates [space option](spaces_option.md) for name separator (`:`).|space after
spaces_around_comma| |Indicates [space option](spaces_option.md) for array value and object name/value pair separators (`,`).|space after
pad_inside_object_braces| |Pad inside object braces|`false`
pad_inside_array_brackets| |Pad inside array brackets|`false`
bigint_format| |Specifies which [bigint format](bigint_chars_format.md) to use when serializing json.|`bignum_format_kind::raw` (since 1.0.0)
bignum_format| |Specifies which [bignum format](bignum_format_kind.md) to use when serializing json. |`bignum_format_kind::raw`
byte_string_format| |Overrides [byte string format](byte_string_chars_format.md) when serializing json. |[byte_string_chars_format::base64url](byte_string_chars_format.md)
float_format| |Overrides [floating point format](float_chars_format.md) when serializing to JSON. |[float_chars_format::general](float_chars_format.md)
precision| |Overrides floating point precision when serializing json.|shortest representation
escape_all_non_ascii| |Escape all non-ascii characters. |`false`
escape_solidus| |Escape the solidus ('/') character. |`false`
new_line_chars| |New line characters|"\n"
line_length_limit| |Line length limit|120
object_object_line_splits| |For an object whose parent is an object, set whether that object is split on a new line, or if its members are split on multiple lines. |[line_split_kind::multi_line](line_split_kind.md)
array_object_line_splits| |For an object whose parent is an array, set whether that object is split on a new line, or if its members are split on multiple lines. |[line_split_kind::multi_line](line_split_kind.md)
object_array_line_splits| |For an array whose parent is an object, set whether that array is split on a new line, or if its elements are split on multiple lines. |[line_split_kind::same_line](line_split_kind.md)
array_array_line_splits| |For an array whose parent is an array, set whether that array is split on a new line, or if its elements are split on multiple lines. |[line_split_kind::new_line](line_split_kind.md)

The default floating point format is [float_chars_format::general](float_chars_format.md).
The default precision is shortest representation, e.g. 1.1 read will remain `1.1` when written, and not become `1.1000000000000001` (an equivalent but longer representation.)
Trailing zeros are removed, except one immediately following the decimal point. The period character (.) is always used as the decimal point, non English locales are ignored.

Aliases for common character types are provided:

Type                |Definition
--------------------|------------------------------
`json_options`        |`basic_json_options<char>`
`wjson_options`       |`basic_json_options<wchar_t>`

#### Member constants

    static const uint8_t indent_size_default = 4;
The default size indent is 4

    static const size_t line_length_limit_default = 120;
The default line length limit is 120

Member type                         |Definition
------------------------------------|------------------------------
`char_type`|`CharT`
`string_type`|`std::basic_string<CharT>`

#### Constructors

    basic_json_options()
Constructs a `basic_json_options` with default values. 

    basic_json_options(const basic_json_options& other)
Copy constructor. 

    basic_json_options(basic_json_options&& other)
Move constructor. 

#### Modifiers

    void max_nesting_depth(int depth)
The maximum nesting depth allowed when decoding and encoding JSON. 
Default is 1024. Parsing can have an arbitrarily large depth
limited only by available memory. Serializing a [basic_json](basic_json.md) to
JSON is limited by stack size.

    basic_json_options& decode_escaped_unicode(bool value); 
Indicates whether to interpret escaped unicode in JSON strings. Defaults to true. 

    basic_json_options& nan_to_str(const string_type& value, bool enable_inverse = true); 
Sets a string replacement for `NaN` when writing JSON, and indicate whether it is also
to be used when reading JSON.

    basic_json_options& inf_to_str(const string_type& value, bool enable_inverse = true); 
Sets a string replacement for infinity when writing JSON, and indicate whether it is also
to be used when reading JSON.

    basic_json_options& neginf_to_str(const string_type& value, bool enable_inverse = true); 
Sets a string replacement for negative infinity when writing JSON, and indicate whether it is also
to be used when reading JSON.

    basic_json_options& nan_to_num(const string_type& value); 
Sets a number replacement for `NaN` when writing JSON

    basic_json_options& inf_to_num(const string_type& value); 
Sets a number replacement for `Infinity` when writing JSON

    basic_json_options& neginf_to_num(const string_type& value); 
Sets a number replacement for `Negative Infinity` when writing JSON

    basic_json_options& lossless_number(bool value); 
If set to `true`, parse numbers with exponents and fractional parts as strings with semantic tagging `semantic_tag::bigdec`.
Defaults to `false`.

    basic_json_options& allow_comments(bool value); 
If set to `true`, an extra comma at the end of a list of JSON values in an object or array is allowed (and ignored).
Defaults to `true`.

    basic_json_options& allow_trailing_comma(bool value); 
If set to `true`, an extra comma at the end of a list of JSON values in an object or array is allowed (and ignored).
Defaults to `false`.

    basic_json_options& indent_size(uint8_t value)
The indent size, the default is 4.

    basic_json_options& spaces_around_colon(spaces_option value)
Indicates [space option](spaces_option.md) for name separator (`:`). Default
is space after.

    basic_json_options& spaces_around_comma(spaces_option value)
Indicates [space option](spaces_option.md) for array value and object name/value pair separators (`,`). Default
is space after.

    basic_json_options& pad_inside_object_braces(bool value)
Default is `false`

    basic_json_options& pad_inside_array_brackets(bool value)
Default is `false`

    basic_json_options& bignum_format(bignum_format_kind value)
Overrides [bignum format](bignum_format_kind.md) when serializing json.
The default is [bignum_format_kind::base10](bignum_format_kind.md). 

    basic_json_options& byte_string_format(byte_string_chars_format value)
Overrides [byte string format](byte_string_chars_format.md) when serializing json.
The default is [byte_string_chars_format::base64url](byte_string_chars_format.md). 

    basic_json_options& float_format(float_chars_format value);
Overrides [floating point format](float_chars_format.md) when serializing to JSON. The default is [float_chars_format::general](float_chars_format.md).

    basic_json_options& precision(int8_t value)
Overrides floating point precision when serializing json. 
The default is shortest representation.

    basic_json_options& escape_all_non_ascii(bool value)
Escape all non-ascii characters. The default is `false`.

    basic_json_options& escape_solidus(bool value)
Escape the solidus ('/') character. The default is `false`.

    basic_json_options& new_line_chars(const string_type& value)
Defaults to "\n"

    basic_json_options& line_length_limit(std::size_t value)

    basic_json_options& object_object_line_splits(line_split_kind value)
For an object whose parent is an object, set whether that object is split on a new line, or if its members are split on multiple lines. The default is [line_split_kind::multi_line](line_split_kind.md).

    basic_json_options& array_object_line_splits(line_split_kind value)
For an object whose parent is an array, set whether that object is split on a new line, or if its members are split on multiple lines. The default is [line_split_kind::multi_line](line_split_kind.md).

    basic_json_options& object_array_line_splits(line_split_kind value)
For an array whose parent is an object, set whether that array is split on a new line, or if its elements are split on multiple lines. The default is [line_split_kind::same_line](line_split_kind.md).

    basic_json_options& array_array_line_splits(line_split_kind value)
For an array whose parent is an array, set whether that array is split on a new line, or if its elements are split on multiple lines. The default is [line_split_kind::new_line](line_split_kind.md).

### Examples

#### Default NaN and inf replacement
```cpp
json obj;
obj["field1"] = std::sqrt(-1.0);
obj["field2"] = 1.79e308*1000;
obj["field3"] = -1.79e308*1000;
std::cout << obj << '\n';
```
Output:
```json
{"field1":null,"field2":null,"field3":null}
```
#### User specified `Nan` and `Inf` replacement

```cpp
json obj;
obj["field1"] = std::sqrt(-1.0);
obj["field2"] = 1.79e308*1000;
obj["field3"] = -1.79e308*1000;

auto options = json_options{}
    .nan_to_num("null");        // default is "null"
    .inf_to_num("1e9999");      // default is "null"

std::cout << pretty_print(obj,options) << '\n';
```

Output:
```json
    {
        "field1":null,
        "field2":1e9999,
        "field3":-1e9999
    }
```

#### Decimal precision

By default, jsoncons parses a number with an exponent or fractional part
into a double precision floating point number. If you wish, you can
keep the number as a string with semantic tagging `bigdec`, 
using the `lossless_number` option. You can then put it into a `float`, 
`double`, a boost multiprecision number, or whatever type you want. 

```cpp
int main()
{
    std::string s = R"(
    {
        "a" : 12.00,
        "b" : 1.23456789012345678901234567890
    }
    )";

    // Default
    json j = json::parse(s);

    std::cout.precision(15);

    // Access as string
    std::cout << "(1) a: " << j["a"].as<std::string>() << ", b: " << j["b"].as<std::string>() << "\n"; 
    // Access as double
    std::cout << "(2) a: " << j["a"].as<double>() << ", b: " << j["b"].as<double>() << "\n\n"; 

    // Using lossless_number option
    auto options = json_options{}
        .lossless_number(true);

    json j2 = json::parse(s, options);
    // Access as string
    std::cout << "(3) a: " << j2["a"].as<std::string>() << ", b: " << j2["b"].as<std::string>() << "\n";
    // Access as double
    std::cout << "(4) a: " << j2["a"].as<double>() << ", b: " << j2["b"].as<double>() << "\n\n"; 
}
```
Output:
```
(1) a: 12.0, b: 1.2345678901234567
(2) a: 12, b: 1.23456789012346

(3) a: 12.00, b: 1.23456789012345678901234567890
(4) a: 12, b: 1.23456789012346
```

#### Object-array block formatting

```cpp
json j;

j["verts"] = json(json_array_arg, {1, 2, 3});
j["normals"] = json(json_array_arg, {1, 0, 1});
j["uvs"] = json(json_array_arg, {0, 0, 1, 1});

std::cout << "Default (same line)" << '\n';
std::cout << pretty_print(j) << '\n';

std::cout << "New line" << '\n';
auto options1 = json_options{}
    .object_array_line_splits(line_split_kind::new_line);
std::cout << pretty_print(j,options1) << '\n';

std::cout << "Multi line" << '\n';
auto options2 = json_options{}
    .object_array_line_splits(line_split_kind::multi_line);
std::cout << pretty_print(j,options2) << '\n';
```

Output:

Default (same line)

```json
{
    "normals": [1,0,1],
    "uvs": [0,0,1,1],
    "verts": [1,2,3]
}
```

New line

```json
{
    "normals": [
        1,0,1
    ],
    "uvs": [
        0,0,1,1
    ],
    "verts": [
        1,2,3
    ]
}
```
Multi line
```json
{
    "normals": [
        1,
        0,
        1
    ],
    "uvs": [
        0,
        0,
        1,
        1
    ],
    "verts": [
        1,
        2,
        3
    ]
}
```

#### Array-array block formatting

```cpp
    json j;
    j["data"]["id"] = json(json_array_arg, {0,1,2,3,4,5,6,7});
    j["data"]["item"] = json(json_array_arg, {json(json_array_arg, {2}),
                                      json(json_array_arg, {4,5,2,3}),
                                      json(json_array_arg, {4}),
                                      json(json_array_arg, {4,5,2,3}),
                                      json(json_array_arg, {2}),
                                      json(json_array_arg, {4,5,3}),
                                      json(json_array_arg, {2}),
                                      json(json_array_arg, {4,3})});

    std::cout << "Default (new line)" << '\n';
    std::cout << pretty_print(j) << '\n';

    std::cout << "Same line" << '\n';
    auto options1 = json_options{}
        .array_array_line_splits(line_split_kind::same_line);
    std::cout << pretty_print(j, options1) << '\n';

    std::cout << "Multi line" << '\n';
    auto options2 = json_options{}
        .array_array_line_splits(line_split_kind::multi_line);
    std::cout << pretty_print(j, options2) << '\n';
```

Output:

Default (new line)

```json
{
    "data": {
        "id": [0,1,2,3,4,5,6,7],
        "item": [
            [2],
            [4,5,2,3],
            [4],
            [4,5,2,3],
            [2],
            [4,5,3],
            [2],
            [4,3]
        ]
    }
}
```
Same line

```json
{
    "data": {
        "id": [0,1,2,3,4,5,6,7],
        "item": [[2],[4,5,2,3],[4],[4,5,2,3],[2],[4,5,3],[2],[4,3]]
    }
}
```

Multi line

```json
{
    "data": {
        "id": [
            0,1,2,3,4,5,6,7
        ],
        "item": [
            [
                2
            ],
            [
                4,
                5,
                2,
                3
            ],
            [
                4
            ],
            [
                4,
                5,
                2,
                3
            ],
            [
                2
            ],
            [
                4,
                5,
                3
            ],
            [
                2
            ],
            [
                4,
                3
            ]
        ]
    }
}
```

#### Allow trailing commas

```cpp
int main()
{
    std::string s = R"(
    {
        "first" : 1,
        "second" : 2,
    }
    )";

    // Default
    try
    {
        auto j = json::parse(s);
    }
    catch (const ser_error& e)
    {
        std::cout << "(1) " << e.what() << "\n\n";
    }

    // Allow trailing commas

    // until 0.170.0
    // auto j = json::parse(s, allow_trailing_commas());

    // since 0.171.0
    // auto options = json_options{}
    //     .err_handler(allow_trailing_commas());
    // auto j = json::parse(s, options);

    // since 1.3.0
    auto options = json_options{}
        .allow_trailing_comma(true));
    auto j = json::parse(s, options);

    std::cout << "(2)" << j << "\n\n";
}
```
Output:
```
(1) Extra comma at line 5 and column 5

(2) {"first":1,"second":2}
```