• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Unchecked access: operator[]
2
3## Overview
4
5Elements in a JSON object and a JSON array can be accessed via `#!cpp operator[]` similar to a `#!cpp std::map` and a `#!cpp std::vector`, respectively.
6
7??? example
8
9    Consider the following JSON value:
10
11    ```json
12    {
13        "name": "Mary Smith",
14        "age": 42,
15        "hobbies": ["hiking", "reading"]
16    }
17    ```
18
19    Assume the value is parsed to a `json` variable `j`.
20
21    | expression | value |
22    | ---------- | ----- |
23    | `#!cpp j`  | `#!json {"name": "Mary Smith", "age": 42, "hobbies": ["hiking", "reading"]}` |
24    | `#!cpp j["name"]`  | `#!json "Mary Smith"` |
25    | `#!cpp j["age"]`  | `#!json 42` |
26    | `#!cpp j["hobbies"]`  | `#!json ["hiking", "reading"]` |
27    | `#!cpp j["hobbies"][0]`  | `#!json "hiking"` |
28    | `#!cpp j["hobbies"][1]`  | `#!json "reading"` |
29
30The return value is a reference, so it can be modify the original value. In case the passed object key is non-existing, a `#!json null` value is inserted which can be immediately be overwritten.
31
32??? example
33
34    ```cpp
35    j["name"] = "John Smith";
36    j["maidenName"] = "Jones";
37    ```
38
39    This code produces the following JSON value:
40
41    ```json
42    {
43        "name": "John Smith",
44        "maidenName": "Jones",
45        "age": 42,
46        "hobbies": ["hiking", "reading"]
47    }
48    ```
49
50When accessing an invalid index (i.e., an index greater than or equal to the array size), the JSON array is resized such that the passed index is the new maximal index. Intermediate values are filled with `#!json null`.
51
52??? example
53
54    ```cpp
55    j["hobbies"][0] = "running";
56    j["hobbies"][3] = "cooking";
57    ```
58
59    This code produces the following JSON value:
60
61    ```json
62    {
63        "name": "John Smith",
64        "maidenName": "Jones",
65        "age": 42,
66        "hobbies": ["running", "reading", null, "cooking"]
67    }
68    ```
69
70## Notes
71
72!!! info "Design rationale"
73
74    The library behaves differently to `#!cpp std::vector` and `#!cpp std::map`:
75
76    - `#!cpp std::vector::operator[]` never inserts a new element.
77    - `#!cpp std::map::operator[]` is not available for const values.
78
79    The type `#!cpp json` wraps all JSON value types. It would be impossible to remove `operator[]` for const objects. At the same time, inserting elements for non-const objects is really convenient as it avoids awkward `insert` calls. To this end, we decided to have an inserting non-const behavior for both arrays and objects.
80
81!!! info
82
83    The access is unchecked. In case the passed object key does not exist or the passed array index is invalid, no exception is thrown.
84
85!!! danger
86
87    - It is **undefined behavior** to access a const object with a non-existing key.
88    - It is **undefined behavior** to access a const array with an invalid index.
89    - In debug mode, an **assertion** will fire in both cases. You can disable assertions by defining the preprocessor symbol `#!cpp NDEBUG` or redefine the macro [`JSON_ASSERT(x)`](../macros.md#json_assertx).
90
91!!! failure "Exceptions"
92
93    `operator[]` can only be used with objects (with a string argument) or with arrays (with a numeric argument). For other types, a [`basic_json::type_error`](../../home/exceptions.md#jsonexceptiontype_error305) is thrown.
94
95## Summary
96
97| scenario | non-const value | const value |
98| -------- | ------------- | ----------- |
99| access to existing object key | reference to existing value is returned | const reference to existing value is returned |
100| access to valid array index | reference to existing value is returned | const reference to existing value is returned |
101| access to non-existing object key | reference to newly inserted `#!json null` value is returned | **undefined behavior**; assertion in debug mode |
102| access to invalid array index | reference to newly inserted `#!json null` value is returned; any index between previous maximal index and passed index are filled with `#!json null` | **undefined behavior**; assertion in debug mode |
103