mirror of
https://github.com/nlohmann/json.git
synced 2026-10-10 16:37:14 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
412d82f6c7 | ||
|
|
26b2494aa7 |
No files matched your search
@@ -337,17 +337,14 @@ def is_remote(url) -> bool:
|
||||
def download(url, docs) -> str:
|
||||
"""Download url into assets/external and return the path relative to docs."""
|
||||
u = urllib.parse.urlparse(url if not url.startswith('//') else 'https:' + url)
|
||||
if u.scheme.lower() not in ('http', 'https'):
|
||||
raise ValueError(f'not an http(s) URL: {url}')
|
||||
req = urllib.request.Request(u.geturl(), headers={'User-Agent': USER_AGENT})
|
||||
# (the scheme is checked above)
|
||||
with urllib.request.urlopen(req, timeout=20) as r: # nosec B310
|
||||
with urllib.request.urlopen(req, timeout=20) as r:
|
||||
data = r.read()
|
||||
ctype = r.headers.get_content_type()
|
||||
path = urllib.parse.unquote(u.path).lstrip('/')
|
||||
ext = os.path.splitext(path)[1]
|
||||
if u.query or not ext or path.endswith('/'):
|
||||
digest = hashlib.sha1(url.encode(), usedforsecurity=False).hexdigest()[:12]
|
||||
digest = hashlib.sha1(url.encode()).hexdigest()[:12]
|
||||
path = os.path.join(os.path.dirname(path), digest + CONTENT_TYPE_EXT.get(ctype, ext or '.bin'))
|
||||
rel = os.path.normpath(os.path.join('assets', 'external', u.hostname, path))
|
||||
out = os.path.join(docs, rel)
|
||||
@@ -388,8 +385,7 @@ def localize_images(docs) -> None:
|
||||
def load_mkdocs_yml() -> dict:
|
||||
"""Load mkdocs.yml, ignoring tags like !ENV and !!python/name."""
|
||||
with open(MKDOCS_YML, encoding='utf-8') as f:
|
||||
# (Loader is a yaml.SafeLoader)
|
||||
return yaml.load(f, Loader=Loader) # nosec B506
|
||||
return yaml.load(f, Loader=Loader)
|
||||
|
||||
|
||||
def localize_site_urls(docs, site_url) -> None:
|
||||
|
||||
@@ -241,4 +241,6 @@ Strong exception safety: if an exception occurs, the original value stays intact
|
||||
3. Added in version 3.11.0. Fixed in version 3.13.0 to consistently accept `std::string_view`-convertible keys, as
|
||||
already supported by [`operator[]`](operator[].md), [`value`](value.md), [`find`](find.md), and other lookup
|
||||
functions.
|
||||
4. Added in version 2.0.0.
|
||||
4. Added in version 2.0.0. Throws [`parse_error.109`](../../home/exceptions.md#jsonexceptionparse_error109) instead of
|
||||
[`out_of_range.404`](../../home/exceptions.md#jsonexceptionout_of_range404) for a one-character array index that is not
|
||||
a digit (e.g., `/x`) in version 3.13.0, as it already did for longer ones.
|
||||
@@ -286,4 +286,6 @@ Strong exception safety: if an exception occurs, the original value stays intact
|
||||
3. Added in version 3.11.0. Fixed in version 3.13.0 to consistently accept `std::string_view`-convertible keys, as
|
||||
already supported by [`at`](at.md), [`value`](value.md), [`find`](find.md), and other lookup functions.
|
||||
4. Added in version 2.0.0. A missing array index in the const version is guarded by a runtime assertion since
|
||||
version 3.13.0.
|
||||
version 3.13.0. Throws [`parse_error.109`](../../home/exceptions.md#jsonexceptionparse_error109) instead of
|
||||
[`out_of_range.404`](../../home/exceptions.md#jsonexceptionout_of_range404) for a one-character array index that is not
|
||||
a digit (e.g., `/x`) in version 3.13.0, as it already did for longer ones.
|
||||
@@ -112,3 +112,6 @@ is thrown. In any case, the original value is not changed: the patch is applied
|
||||
location has a non-object/non-array parent in version 3.13.0.
|
||||
- Added [`out_of_range.414`](../../home/exceptions.md#jsonexceptionout_of_range414) and rejected a "move" operation whose "from" location is a proper
|
||||
prefix of its "path" location instead of silently producing a corrupted result in version 3.13.0.
|
||||
- Throws [`parse_error.109`](../../home/exceptions.md#jsonexceptionparse_error109) instead of
|
||||
[`out_of_range.404`](../../home/exceptions.md#jsonexceptionout_of_range404) for a one-character array index that is
|
||||
not a digit (e.g., `/x`) in version 3.13.0, as it already did for longer ones.
|
||||
@@ -110,3 +110,6 @@ function throws an exception.
|
||||
location has a non-object/non-array parent in version 3.13.0.
|
||||
- Added [`out_of_range.414`](../../home/exceptions.md#jsonexceptionout_of_range414) and rejected a "move" operation whose "from" location is a proper
|
||||
prefix of its "path" location instead of silently producing a corrupted result in version 3.13.0.
|
||||
- Throws [`parse_error.109`](../../home/exceptions.md#jsonexceptionparse_error109) instead of
|
||||
[`out_of_range.404`](../../home/exceptions.md#jsonexceptionout_of_range404) for a one-character array index that is
|
||||
not a digit (e.g., `/x`) in version 3.13.0, as it already did for longer ones.
|
||||
@@ -36,8 +36,9 @@ The function can throw the following exceptions:
|
||||
- Throws [`parse_error.109`](../../home/exceptions.md#jsonexceptionparse_error109) if an array index in a key is not a
|
||||
number; example: `"array index 'one' is not a number"`
|
||||
- Throws [`out_of_range.404`](../../home/exceptions.md#jsonexceptionout_of_range404) if a level becomes an array
|
||||
(because one of its keys is `0`) and another key at that level cannot be an array index; example:
|
||||
`"unresolved reference token 'x'"`
|
||||
(because one of its keys is `0`) and another key at that level begins with a digit but is not a valid array index
|
||||
(such as `1a`), or is `-`; example:
|
||||
`"unresolved reference token '-'"`
|
||||
|
||||
## Complexity
|
||||
|
||||
@@ -80,3 +81,6 @@ Apart from these two cases, for a JSON value `j`, the following is always true:
|
||||
|
||||
- Added in version 2.0.0.
|
||||
- Made the array/object decision independent of the object's iteration order in version 3.13.0.
|
||||
- Throws [`parse_error.109`](../../home/exceptions.md#jsonexceptionparse_error109) instead of
|
||||
[`out_of_range.404`](../../home/exceptions.md#jsonexceptionout_of_range404) for a one-character array index that is
|
||||
not a digit (e.g., `/x`) in version 3.13.0, as it already did for longer ones.
|
||||
@@ -119,14 +119,6 @@ changes to any JSON value.
|
||||
|
||||
## Notes
|
||||
|
||||
!!! warning "`null` members are not missing"
|
||||
|
||||
The default value is used only if the key (or JSON Pointer) does not exist. A member that exists but is
|
||||
`#!json null` is converted like any other value, so `#!cpp j.value("k", 0)` throws a
|
||||
[`type_error.302`](../../home/exceptions.md#jsonexceptiontype_error302) if `"k"` is `#!json null`. See
|
||||
[Access with default value](../../features/element_access/default_value.md)
|
||||
for alternatives.
|
||||
|
||||
!!! warning "Return type"
|
||||
|
||||
The value function is a template, and the return type of the function is determined by the type of the provided
|
||||
@@ -235,4 +227,6 @@ changes to any JSON value.
|
||||
[`operator[]`](operator[].md), [`at`](at.md), [`find`](find.md), and other lookup functions.
|
||||
3. Added in version 2.0.2. Extended to work with arrays in version 3.13.0, including fixing an issue where resolving
|
||||
`ptr` through an array unexpectedly threw `out_of_range` instead of returning the resolved element (or
|
||||
`default_value`, as documented).
|
||||
`default_value`, as documented). Throws [`parse_error.109`](../../home/exceptions.md#jsonexceptionparse_error109)
|
||||
instead of returning `default_value` for a one-character array index that is not a digit (e.g., `/x`) in version
|
||||
3.13.0, as it already did for longer ones.
|
||||
@@ -347,13 +347,6 @@ struct adl_serializer<boost::optional<T>> {
|
||||
NLOHMANN_JSON_NAMESPACE_END
|
||||
```
|
||||
|
||||
!!! tip "`std::optional` needs no serializer"
|
||||
|
||||
Since version 3.12.0, `std::optional<T>` is supported out of the box when compiling with C++17
|
||||
(`std::nullopt` is converted to and from `null`). Do not write an `adl_serializer` for it; this pattern is only
|
||||
needed for types such as `boost::optional` or for custom semantics. See [Conversions](conversions.md) and
|
||||
[Omitting a field when serializing `std::optional`](conversions.md#omitting-a-field-when-serializing-stdoptional).
|
||||
|
||||
!!! note "ABI compatibility"
|
||||
|
||||
Use [`NLOHMANN_JSON_NAMESPACE_BEGIN`](../api/macros/nlohmann_json_namespace_begin.md) and `NLOHMANN_JSON_NAMESPACE_END`
|
||||
|
||||
@@ -30,47 +30,6 @@ you want to access and a default value in case there is no value stored with tha
|
||||
| `#!cpp j.value("append", false)` | `#!json true` |
|
||||
| `#!cpp j.value("logLevel", "verbose")` | `#!json "verbose"` |
|
||||
|
||||
## Nested values
|
||||
|
||||
To read a value deep inside a document, pass a [JSON Pointer](../json_pointer.md) instead of a key. The default value is
|
||||
returned if the value at the pointer does not exist, including the case that an intermediate key is missing. There is
|
||||
no need to check each level with [`contains`](../../api/basic_json/contains.md) first.
|
||||
|
||||
```cpp
|
||||
json j = {{"server", {{"port", 8080}}}, {"list", {10, 20}}};
|
||||
|
||||
int port = j.value("/server/port"_json_pointer, 80); // 8080
|
||||
int timeout = j.value("/server/limits/timeout"_json_pointer, 30); // 30 (missing intermediate key)
|
||||
int second = j.value("/list/1"_json_pointer, 0); // 20 (numeric tokens index arrays)
|
||||
int third = j.value("/list/5"_json_pointer, 0); // 0 (index out of range)
|
||||
|
||||
bool has_port = j.contains("/server/port"_json_pointer); // true
|
||||
bool has_host = j.contains("/server/host/name"_json_pointer); // false
|
||||
```
|
||||
|
||||
If the path is only available as a dotted string such as `#!cpp "server.port"`, do not build the pointer by
|
||||
concatenating `#!cpp "/"` and the parts: keys containing `/` or `~` would be misinterpreted. Append each part as a
|
||||
reference token with [`operator/=`](../../api/json_pointer/operator_slasheq.md) instead. It escapes the token for you.
|
||||
|
||||
```cpp
|
||||
json::json_pointer to_pointer(const std::string& dotted)
|
||||
{
|
||||
json::json_pointer ptr;
|
||||
std::istringstream in(dotted);
|
||||
for (std::string token; std::getline(in, token, '.');)
|
||||
{
|
||||
ptr /= token;
|
||||
}
|
||||
return ptr;
|
||||
}
|
||||
|
||||
int port = j.value(to_pointer("server.port"), 80); // 8080
|
||||
int first = j.value(to_pointer("list.0"), 0); // 10
|
||||
```
|
||||
|
||||
The key `#!cpp "a/b"` yields the pointer `#!cpp "/a~1b"`; the dot-splitting itself is up to the caller, so keys
|
||||
containing `.` need a different separator.
|
||||
|
||||
## Notes
|
||||
|
||||
!!! failure "Exceptions"
|
||||
@@ -78,31 +37,6 @@ containing `.` need a different separator.
|
||||
- With string keys, `value` can only be used with objects. For other types, a [`basic_json::type_error`](../../home/exceptions.md#jsonexceptiontype_error306) is thrown.
|
||||
- With JSON Pointers, `value` can be used with both objects and arrays. For other types (null, boolean, number, string), a [`basic_json::type_error`](../../home/exceptions.md#jsonexceptiontype_error306) is thrown.
|
||||
|
||||
!!! warning "`null` and mistyped members are not missing"
|
||||
|
||||
`value` returns the default value only if the key is **absent**. If the member exists, it is converted to the type
|
||||
of the default value, even if it is `#!json null`. For `#!json {"k": null}`, the call `#!cpp j.value("k", 0)` throws
|
||||
a [`basic_json::type_error`](../../home/exceptions.md#jsonexceptiontype_error302), and so does a member of another
|
||||
type such as a string where a number is expected. The same holds for JSON Pointers.
|
||||
|
||||
To treat `#!json null` like a missing value, check for it explicitly:
|
||||
|
||||
```cpp
|
||||
int n = (j.contains("k") && !j["k"].is_null()) ? j["k"].get<int>() : 0;
|
||||
```
|
||||
|
||||
With C++17, [`get<std::optional<T>>()`](../../api/basic_json/get.md) maps `#!json null` to an empty optional. As
|
||||
[`at`](../../api/basic_json/at.md) throws [`out_of_range`](../../home/exceptions.md#jsonexceptionout_of_range403)
|
||||
for an absent key, use [`find`](../../api/basic_json/find.md) to cover both cases:
|
||||
|
||||
```cpp
|
||||
std::optional<int> n; // empty if "k" is absent or null
|
||||
if (const auto it = j.find("k"); it != j.end())
|
||||
{
|
||||
n = it->get<std::optional<int>>(); // still throws for a non-number such as "text"
|
||||
}
|
||||
```
|
||||
|
||||
!!! warning "Return type"
|
||||
|
||||
The value function is a template, and the return type of the function is determined by the type of the provided
|
||||
@@ -129,6 +63,3 @@ containing `.` need a different separator.
|
||||
|
||||
- [`value`](../../api/basic_json/value.md) for access with default value
|
||||
- documentation on [checked access](checked_access.md)
|
||||
- documentation on [JSON Pointer](../json_pointer.md)
|
||||
- [`contains`](../../api/basic_json/contains.md) to check whether a key or JSON Pointer exists
|
||||
- [`json_pointer::operator/=`](../../api/json_pointer/operator_slasheq.md) to build a pointer token by token
|
||||
@@ -77,10 +77,6 @@ auto val2 = j.at(json::json_pointer("/nested/three/1")); // false
|
||||
auto val3 = j.value(json::json_pointer("/nested/four"), 0); // 0
|
||||
```
|
||||
|
||||
To read a value with a fallback, use [`value`](../api/basic_json/value.md) with a JSON Pointer; to test for existence,
|
||||
use [`contains`](../api/basic_json/contains.md). Neither needs intermediate checks, see
|
||||
[Nested values](element_access/default_value.md#nested-values).
|
||||
|
||||
!!! note "Creating intermediate levels that don't exist"
|
||||
|
||||
See the [`operator[]` notes](../api/basic_json/operator%5B%5D.md#return-value) for how array vs. object is
|
||||
@@ -130,8 +126,6 @@ auto j_original = j_flat.unflatten();
|
||||
## See also
|
||||
|
||||
- Class [`json_pointer`](../api/json_pointer/index.md)
|
||||
- Functions [`value`](../api/basic_json/value.md), [`contains`](../api/basic_json/contains.md), and
|
||||
[`at`](../api/basic_json/at.md) accept JSON Pointers; see [Nested values](element_access/default_value.md#nested-values)
|
||||
- Function [`flatten`](../api/basic_json/flatten.md)
|
||||
- Function [`unflatten`](../api/basic_json/unflatten.md)
|
||||
- [JSON Patch](json_patch.md) - paths inside a patch are JSON Pointers
|
||||
|
||||
@@ -9,13 +9,6 @@ syntax that closely mimics the document being modified. Unlike [JSON Patch](json
|
||||
express every kind of change (e.g., it cannot reorder array elements or remove a specific array element), but it is
|
||||
easier to read and write for object-shaped documents.
|
||||
|
||||
!!! tip "Not a general deep merge"
|
||||
|
||||
A merge patch is not a general deep merge: a `#!json null` value in the patch deletes the key from the target.
|
||||
To merge two objects recursively (e.g., defaults and user settings), use
|
||||
[`update`](../api/basic_json/update.md) with `merge_objects` set to `#!cpp true`; see
|
||||
[Merging objects](modifying_values.md#merging-objects).
|
||||
|
||||
??? example
|
||||
|
||||
The following code shows how a JSON Merge Patch is applied to a JSON document.
|
||||
@@ -35,4 +28,3 @@ easier to read and write for object-shaped documents.
|
||||
- [JSON Patch and Diff](json_patch.md) - a more expressive alternative that describes a sequence of operations
|
||||
- [JSON Pointer](json_pointer.md) - the addressing scheme used by JSON Patch
|
||||
- Function [`merge_patch`](../api/basic_json/merge_patch.md)
|
||||
- Function [`update`](../api/basic_json/update.md) - merge objects, optionally recursively
|
||||
@@ -35,12 +35,8 @@ the insertion happened — useful for "add if absent" semantics.
|
||||
|
||||
## Merging objects
|
||||
|
||||
To merge one object into another, [`update`](../api/basic_json/update.md) copies all members from another object
|
||||
(similar to Python's `dict.update`). This is the idiomatic way to combine two objects. It has two modes:
|
||||
|
||||
- By default, the merge is shallow: existing keys are overwritten, even if both values are objects.
|
||||
- With `merge_objects = #!cpp true`, keys whose values are objects in both JSON values are merged recursively.
|
||||
Everything else is overwritten. In particular, arrays are replaced, not concatenated.
|
||||
To merge one object into another, [`update`](../api/basic_json/update.md) copies all members from another object,
|
||||
overwriting existing keys (similar to Python's `dict.update`). This is the idiomatic way to combine two objects.
|
||||
|
||||
??? example
|
||||
|
||||
@@ -54,22 +50,9 @@ To merge one object into another, [`update`](../api/basic_json/update.md) copies
|
||||
--8<-- "examples/update.output"
|
||||
```
|
||||
|
||||
A common use of the recursive mode is combining defaults with user settings. Nested defaults that the user did not set
|
||||
are kept:
|
||||
|
||||
```cpp
|
||||
json defaults = {{"log", {{"level", "info"}, {"file", "app.log"}}}, {"retries", 3}};
|
||||
json user_settings = {{"log", {{"level", "debug"}}}};
|
||||
|
||||
json config = defaults;
|
||||
config.update(user_settings, true);
|
||||
// {"log":{"file":"app.log","level":"debug"},"retries":3}
|
||||
```
|
||||
|
||||
[JSON Merge Patch](merge_patch.md) ([RFC 7386](https://tools.ietf.org/html/rfc7386)) also merges objects recursively,
|
||||
but it is a different tool: a `#!json null` in the patch means "remove this key". It is meant for applying merge patch
|
||||
documents (e.g., received via HTTP PATCH). To merge configuration-like objects, use `#!cpp update(..., true)`. To apply
|
||||
a sequence of well-defined edit operations, see [JSON Patch](json_patch.md).
|
||||
For a recursive merge that follows [RFC 7386](https://tools.ietf.org/html/rfc7386), see
|
||||
[JSON Merge Patch](merge_patch.md). To apply a sequence of well-defined edit operations, see
|
||||
[JSON Patch](json_patch.md).
|
||||
|
||||
## Removing elements
|
||||
|
||||
@@ -89,7 +72,6 @@ a.erase(1); // [1,3,4] (erase by index)
|
||||
|
||||
- [`push_back`](../api/basic_json/push_back.md) / [`emplace_back`](../api/basic_json/emplace_back.md) - append to an array
|
||||
- [`emplace`](../api/basic_json/emplace.md) - insert into an object if the key is absent
|
||||
- [`update`](../api/basic_json/update.md) - merge objects (shallow, or recursive with `merge_objects`)
|
||||
- [`merge_patch`](../api/basic_json/merge_patch.md) - apply an RFC 7386 merge patch
|
||||
- [`update`](../api/basic_json/update.md) - merge objects
|
||||
- [`erase`](../api/basic_json/erase.md) / [`clear`](../api/basic_json/clear.md) - remove elements
|
||||
- [JSON Patch and Diff](json_patch.md) and [JSON Merge Patch](merge_patch.md) - structured modifications
|
||||
@@ -278,7 +278,9 @@ In a JSON Pointer, only `~0` and `~1` are valid escape sequences.
|
||||
|
||||
### json.exception.parse_error.109
|
||||
|
||||
A JSON Pointer array index must be a number.
|
||||
A JSON Pointer array index must be a number. This exception is thrown for an array index that does not begin with a
|
||||
digit, except for `-` and the empty reference token, which throw [`out_of_range.404`](#jsonexceptionout_of_range404)
|
||||
where they cannot be resolved.
|
||||
|
||||
!!! failure "Example messages"
|
||||
|
||||
@@ -289,6 +291,11 @@ A JSON Pointer array index must be a number.
|
||||
[json.exception.parse_error.109] parse error: array index '+1' is not a number
|
||||
```
|
||||
|
||||
!!! note
|
||||
|
||||
Before version 3.13.0, a one-character array index that is not a digit (e.g., `x`) threw
|
||||
[`out_of_range.404`](#jsonexceptionout_of_range404) instead.
|
||||
|
||||
### json.exception.parse_error.110
|
||||
|
||||
When parsing a [binary format](../features/binary_formats/index.md), the byte vector ends before the complete value has
|
||||
@@ -871,7 +878,8 @@ The provided key was not found in the JSON object.
|
||||
|
||||
### json.exception.out_of_range.404
|
||||
|
||||
A reference token in a JSON Pointer could not be resolved.
|
||||
A reference token in a JSON Pointer could not be resolved, for instance an array index that begins with a digit but
|
||||
contains other characters (e.g., `1a`), or `-` where it cannot be used.
|
||||
|
||||
!!! failure "Example message"
|
||||
|
||||
|
||||
@@ -255,7 +255,7 @@ class json_pointer
|
||||
{
|
||||
ok, ///< @a s is a valid, representable array index
|
||||
leading_zero, ///< @a s begins with '0' but has more than one character
|
||||
not_a_number, ///< @a s does not begin with a digit
|
||||
not_a_number, ///< @a s is neither empty nor "-" and does not begin with a digit
|
||||
unresolved, ///< @a s could not be converted to an integer
|
||||
exceeds_size_type ///< @a s converts to an integer that exceeds size_type
|
||||
};
|
||||
@@ -282,8 +282,10 @@ class json_pointer
|
||||
return array_index_status::leading_zero;
|
||||
}
|
||||
|
||||
// error condition (cf. RFC 6901, Sect. 4)
|
||||
if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9')))
|
||||
// error condition (cf. RFC 6901, Sect. 4); this also covers single-
|
||||
// character tokens, so "/x" and "/xy" fail alike; "-" and the empty
|
||||
// token are left to the conversion below and are reported as unresolved
|
||||
if (JSON_HEDLEY_UNLIKELY(!s.empty() && s != "-" && !(s[0] >= '0' && s[0] <= '9')))
|
||||
{
|
||||
return array_index_status::not_a_number;
|
||||
}
|
||||
|
||||
@@ -247,6 +247,14 @@ public:
|
||||
// ^ ^
|
||||
// first last
|
||||
|
||||
// Note on conformance: before C++20, [basic.life]/8 did not allow an
|
||||
// object of a type with a const member (like value_type's const Key)
|
||||
// to transparently replace the destroyed one, so strictly, accessing
|
||||
// it through the vector's existing pointers would have required
|
||||
// std::launder (which does not exist before C++17). C++20 dropped that
|
||||
// condition (P1971R0, NB comment US 041). Compilers have always treated
|
||||
// this pattern as intended, so it is kept deliberately.
|
||||
|
||||
// Since we cannot move const Keys, we re-construct them in place.
|
||||
// We start at first and re-construct (viz. copy) the elements from
|
||||
// the back of the vector. Example for the first iteration:
|
||||
|
||||
@@ -20173,7 +20173,7 @@ class json_pointer
|
||||
{
|
||||
ok, ///< @a s is a valid, representable array index
|
||||
leading_zero, ///< @a s begins with '0' but has more than one character
|
||||
not_a_number, ///< @a s does not begin with a digit
|
||||
not_a_number, ///< @a s is neither empty nor "-" and does not begin with a digit
|
||||
unresolved, ///< @a s could not be converted to an integer
|
||||
exceeds_size_type ///< @a s converts to an integer that exceeds size_type
|
||||
};
|
||||
@@ -20200,8 +20200,10 @@ class json_pointer
|
||||
return array_index_status::leading_zero;
|
||||
}
|
||||
|
||||
// error condition (cf. RFC 6901, Sect. 4)
|
||||
if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9')))
|
||||
// error condition (cf. RFC 6901, Sect. 4); this also covers single-
|
||||
// character tokens, so "/x" and "/xy" fail alike; "-" and the empty
|
||||
// token are left to the conversion below and are reported as unresolved
|
||||
if (JSON_HEDLEY_UNLIKELY(!s.empty() && s != "-" && !(s[0] >= '0' && s[0] <= '9')))
|
||||
{
|
||||
return array_index_status::not_a_number;
|
||||
}
|
||||
@@ -27780,6 +27782,14 @@ public:
|
||||
// ^ ^
|
||||
// first last
|
||||
|
||||
// Note on conformance: before C++20, [basic.life]/8 did not allow an
|
||||
// object of a type with a const member (like value_type's const Key)
|
||||
// to transparently replace the destroyed one, so strictly, accessing
|
||||
// it through the vector's existing pointers would have required
|
||||
// std::launder (which does not exist before C++17). C++20 dropped that
|
||||
// condition (P1971R0, NB comment US 041). Compilers have always treated
|
||||
// this pattern as intended, so it is kept deliberately.
|
||||
|
||||
// Since we cannot move const Keys, we re-construct them in place.
|
||||
// We start at first and re-construct (viz. copy) the elements from
|
||||
// the back of the vector. Example for the first iteration:
|
||||
|
||||
@@ -535,6 +535,8 @@ TEST_CASE_TEMPLATE("element access 2", Json, nlohmann::json, nlohmann::ordered_j
|
||||
// Test malformed index (non-numeric) throws parse_error
|
||||
CHECK_THROWS_WITH_AS(j_array.value("/foo"_json_pointer, 1), "[json.exception.parse_error.109] parse error: array index 'foo' is not a number", typename Json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(j_array_const.value("/foo"_json_pointer, 1), "[json.exception.parse_error.109] parse error: array index 'foo' is not a number", typename Json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(j_array.value("/x"_json_pointer, 1), "[json.exception.parse_error.109] parse error: array index 'x' is not a number", typename Json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(j_array_const.value("/x"_json_pointer, 1), "[json.exception.parse_error.109] parse error: array index 'x' is not a number", typename Json::parse_error&);
|
||||
|
||||
// Test leading-zero index throws parse_error
|
||||
CHECK_THROWS_WITH_AS(j_array.value("/01"_json_pointer, 1), "[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'", typename Json::parse_error&);
|
||||
|
||||
@@ -1713,6 +1713,21 @@ TEST_CASE("JSON patch - move where 'from' is a proper prefix of 'path' (regressi
|
||||
CHECK(doc.patch(patch) == R"({"b": 1})"_json);
|
||||
}
|
||||
|
||||
SECTION("array index tokens that are not a number")
|
||||
{
|
||||
json const doc = R"({"a": [1, 2]})"_json;
|
||||
|
||||
// "-" cannot be removed and is reported as unresolved
|
||||
json const patch_dash = {{{"op", "remove"}, {"path", "/a/-"}}};
|
||||
CHECK_THROWS_WITH_AS(doc.patch(patch_dash), "[json.exception.out_of_range.404] unresolved reference token '-'", json::out_of_range&);
|
||||
|
||||
// a single character is reported like a longer token
|
||||
json const patch_x = {{{"op", "remove"}, {"path", "/a/x"}}};
|
||||
CHECK_THROWS_WITH_AS(doc.patch(patch_x), "[json.exception.parse_error.109] parse error: array index 'x' is not a number", json::parse_error&);
|
||||
json const patch_xy = {{{"op", "remove"}, {"path", "/a/xy"}}};
|
||||
CHECK_THROWS_WITH_AS(doc.patch(patch_xy), "[json.exception.parse_error.109] parse error: array index 'xy' is not a number", json::parse_error&);
|
||||
}
|
||||
|
||||
SECTION("the array-append token '-' is an ordinary child token")
|
||||
{
|
||||
// "-" (append-to-array) addresses a location *inside* the array,
|
||||
|
||||
@@ -421,6 +421,27 @@ TEST_CASE("JSON pointers")
|
||||
CHECK_THROWS_WITH_AS(json({{"/list/0", 1}, {"/list/1", 2}, {"/list/three", 3}}).unflatten(),
|
||||
"[json.exception.parse_error.109] parse error: array index 'three' is not a number", json::parse_error&);
|
||||
|
||||
// a single-character token that is not a digit is reported like a
|
||||
// longer one (parse_error.109), not as unresolved (out_of_range.404)
|
||||
CHECK_THROWS_WITH_AS(j["/x"_json_pointer] = 1,
|
||||
"[json.exception.parse_error.109] parse error: array index 'x' is not a number", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(j_const["/x"_json_pointer] == 1,
|
||||
"[json.exception.parse_error.109] parse error: array index 'x' is not a number", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(j.at("/x"_json_pointer) = 1,
|
||||
"[json.exception.parse_error.109] parse error: array index 'x' is not a number", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(j_const.at("/x"_json_pointer) == 1,
|
||||
"[json.exception.parse_error.109] parse error: array index 'x' is not a number", json::parse_error&);
|
||||
CHECK_THROWS_WITH_AS(j.at("/+"_json_pointer),
|
||||
"[json.exception.parse_error.109] parse error: array index '+' is not a number", json::parse_error&);
|
||||
CHECK(!j.contains("/x"_json_pointer));
|
||||
CHECK(!j_const.contains("/x"_json_pointer));
|
||||
CHECK_THROWS_WITH_AS(json({{"/list/0", 1}, {"/list/x", 2}}).unflatten(),
|
||||
"[json.exception.parse_error.109] parse error: array index 'x' is not a number", json::parse_error&);
|
||||
|
||||
// "-" is a valid reference token, so it is still reported as unresolved
|
||||
CHECK_THROWS_WITH_AS(json({{"/list/0", 1}, {"/list/-", 2}}).unflatten(),
|
||||
"[json.exception.out_of_range.404] unresolved reference token '-'", json::out_of_range&);
|
||||
|
||||
// assign to "-"
|
||||
j["/-"_json_pointer] = 99;
|
||||
CHECK(j == json({1, 13, 3, 33, nullptr, 55, 99}));
|
||||
|
||||
Reference in new issue
Block a user