Add API reference pages for basic_json_document::insert and basic_json_document::erase, matching the style of set.md and push_back.md: signatures, parameters, return values, exception safety, exceptions with their exact ids and messages, complexity, notes on duplicate keys and view/iterator validity, and an example. Add example programs basic_json_document__insert.cpp and basic_json_document__erase.cpp with their expected output, each comparing an edit on an editable document with the same edit on a plain json value to show what is preserved: member order, the spelling of untouched numbers, and, for insert, that a view taken before the insert keeps referring to the same element after its index shifts. Register both new pages in mkdocs.yml, docSet.sql, and the member list of basic_json_document/index.md, add cross-references to them from set.md and push_back.md, and mention insert/erase in the "Editing a document" section of features/json_view.md. Signed-off-by: Niels Lohmann <mail@nlohmann.me>
10 KiB
nlohmann::basic_json_document::set
// (1)
template<typename V>
view_type set(view_type target, V&& value);
// (2)
template<typename V>
view_type set(view_type object, string_view_t key, V&& value);
// (3)
template<typename I, typename V>
view_type set(view_type array, I idx, V&& value);
// (4)
template<typename V>
view_type set(const json_pointer& ptr, V&& value);
Only an editable document (#!cpp Editable == true, e.g. json_editable_document)
has set; calling it on a read-only basic_json_document fails to compile (#!cpp static_assert).
- Replaces the value
targetrefers to withvalue. - Sets the member
keyof the objectobjecttovalue: assigns it ifobjectalready has a member with this key -- the first one, should the key occur more than once, and the later duplicates are then dropped (see the Notes below) -- or appends a new member at the end otherwise. A nullobjectfirst becomes an empty object. - Assigns
valueto the element at indexidxof the arrayarray, which must already exist (#!cpp idx < array.size()). - Sets the value the JSON pointer
ptrrefers to, relative toroot(), tovalue. The parent of the target must already exist: an object member is set as in 2. (added if it does not exist yet), an array element is assigned as in 3., and a last reference token of#!cpp "-", or equal to the size of the array, appendsvalueinstead, exactly aspush_backwould. An emptyptrsetsroot()itself, as in 1.
In every overload, value is accepted three ways: a basic_json_view of any
document -- read-only or editable, and it does not have to be target's/object's/array's own document -- which
is copied so that nothing is shared with the source document afterward; a BasicJsonType value; or anything
BasicJsonType can be constructed from (numbers, strings, #!cpp bool, #!cpp nullptr, containers, ...).
Template parameters
V- the type of
value, deduced; see above for what is accepted. I- an integral type other than
#!cpp bool, deduced (overloads taking a#!cpp boolor a non-integral type foridxdo not participate in overload resolution).
Parameters
target(in)- the value to replace
object(in)- the object (or null value) whose member to set
array(in)- the array whose element to assign
key(in)- the key of the member to set
idx(in)- the index of the element to assign; a negative value throws (see Exceptions)
ptr(in)- a JSON pointer to the value to set, relative to
root() value(in)- the new value
Return value
- a view of
target, now holdingvalue - a view of the member
keyofobject, now holdingvalue - a view of the element
idxofarray, now holdingvalue - a view of the value
ptrrefers to, now holdingvalue
Exception safety
Basic exception safety: value is fully encoded -- including the checks below -- into storage owned by the document
before anything already reachable from root() is touched, so a failure while encoding value (an
invalid argument, or #!cpp std::bad_alloc) leaves the document completely unchanged, other than memory allocated
for the encoding that is not reclaimed. A failure of a later allocation -- while an edited array or object switches
from its parsed layout to a growable block, see Notes -- can still leave a partial effect, such as a
null object/array argument already turned into an empty object/array even
though value itself was not linked in.
Exceptions
- Throws
type_error.302ifvalueis a discarded view, or a discardedBasicJsonTypevalue (e.g.#!cpp BasicJsonType(value_t::discarded)) -- an object or arrayvalue, of either kind, is fine and is encoded as a whole subtree. - Throws
type_error.305ifobjectis neither an object nor null -- the same messageoperator[]throws for a string argument on such a value. Throwstype_error.316ifkeyis not valid UTF-8, with the same messageBasicJsonType::dump()gives for that string. Also throws what 1. throws forvalue. - Throws
type_error.305ifarrayis not an array -- the same messageoperator[]throws for a numeric argument on such a value. Throwsout_of_range.401ifidxis negative, or if#!cpp idx >= array.size(). Also throws what 1. throws forvalue. - Throws what
atthrows (overload 3) for resolvingptr's parent, except that a missing object member or an array index equal to the array's size at the very last reference token is not an error there (it becomes a new member or an appended element) instead ofout_of_range.403/out_of_range.402. For the last reference token itself: if the parent is an object (or a primitive value, where it throwstype_error.305), throws what 2. throws; if the parent is an array, throws what 3. throws for an index that is out of range, or, for a token that is not a valid array index,parse_error.106(a leading#!cpp '0'),parse_error.109(not a number),out_of_range.410(too large forsize_type), orout_of_range.404(an empty token). Also throws what 1. throws forvalue.
Every overload also throws type_error.319 if value is (or
contains) a binary value -- BasicJsonType can hold one, but a json_document cannot -- and
invalid_iterator.202 ("view does not belong to this
document") if target/object/array is a discarded view or a view of a
different document (overloads 1-3 only; overload 4 always starts from this document's own root()).
Complexity
- Linear in the size of
value(encoding it into the document's storage): constant for a scalar, linear in the number of nested values for an array or object. Iftargetis itself an array or object that spans more than one node in its parent's original, unedited layout, andvalueis a scalar, replacing it additionally costs time linear in the number of elements of that parent, the first time -- see Notes. - Linear in the number of members of
object, to find an existing member withkey, plus the complexity of 1. forvalue. - Constant, plus the complexity of 1. for
value. - Linear in the number of reference tokens of
ptrand, for each token, in the number of members of the object at that level or the index into the array (asat), plus the complexity of 2. or 3. for the last token.
Notes
!!! info "Duplicate keys"
If `object` already has more than one member with `key` (2.), the *first* one is assigned `value` and every
later member with the same key is removed -- so that a lookup, an iteration, and
[`materialize()`](../basic_json_view/materialize.md) of `object` afterward all agree on a single value for
`key`, the same way [`operator[]`](../basic_json_view/operator%5B%5D.md) already picks the first occurrence of a
duplicate key for reading. See the [Notes on duplicate keys](../basic_json_view/operator%5B%5D.md#notes) of
`operator[]`.
Setting a member (2.) or an element (3., through 4.) of an array or object whose elements have not been edited
before switches it from its parsed layout to a growable block holding links to its elements; a later
push_back or set on the same container reuses that block, growing it (amortized constant time)
only once it runs out of room. This never moves an element itself -- only where the container's links to its
elements live -- so a view of an element stays valid, but any iterator already taken over the container is
invalidated, since it was walking the old layout. See Edits for what stays valid across an edit in
general.
The same switch happens, for the same reason, when overload 1. replaces a multi-node array/object value with a
scalar: the parent's element sequence is what has to switch to links, not target itself, because the parent
originally stepped over target's whole subtree by its node count, which no longer applies once target is a
one-node scalar.
Examples
??? example "Example: (1)/(2)/(3)/(4) replace a value, set a member, assign an element, set via a JSON pointer"
The example below edits a small configuration document -- replacing a value, adding an object member, assigning
an array element, and reaching a field through a JSON pointer -- and shows what
[`dump()`](../basic_json_view/dump.md) preserves that is lost once the same edits are made on a `BasicJsonType`
value instead: the order object members were written in, and the exact spelling of a number that was never
touched.
```cpp
--8<-- "examples/basic_json_document__set.cpp"
```
Output:
```json
--8<-- "examples/basic_json_document__set.output"
```
See also
- push_back - append to an array
- insert - insert an element into an array
- erase - remove an object member, an array element, or the value a JSON pointer refers to
- root - the view of the root value, the starting point of overload 4
basic_json_view::dump- serialize the document, keeping an untouched number's spelling with#!cpp number_format::source- Edits - what an edit guarantees, for every overload
- Editing a document - why editable documents keep the source text's order and number spelling
Version history
- Added in version 3.13.0.