Compare commits

...
Author SHA1 Message Date
Niels Lohmann c1945cb8d5 Do not throw in contains() for an empty array reference token
json_pointer::contains() rejected malformed array indices, but an empty
reference token (e.g. "/a/" where "a" is an array, or "/" on an array)
passed every check and reached array_index(), which throws
out_of_range.404. contains() must not throw (cf. #5395), so it now
returns false for an empty token. at() still throws out_of_range.404.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-09-29 06:37:09 +02:00
3 changed files with 32 additions and 0 deletions
+6
View File
@@ -746,6 +746,12 @@ class json_pointer
// "-" always fails the range check
return false;
}
if (JSON_HEDLEY_UNLIKELY(reference_token.empty()))
{
// an empty reference token is not an array index; array_index()
// would throw out_of_range.404 -- contains() must not throw (see #5395)
return false;
}
if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9")))
{
// invalid char
+6
View File
@@ -19588,6 +19588,12 @@ class json_pointer
// "-" always fails the range check
return false;
}
if (JSON_HEDLEY_UNLIKELY(reference_token.empty()))
{
// an empty reference token is not an array index; array_index()
// would throw out_of_range.404 -- contains() must not throw (see #5395)
return false;
}
if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9")))
{
// invalid char
+20
View File
@@ -380,6 +380,26 @@ TEST_CASE("JSON pointers")
DOCTEST_MSVC_SUPPRESS_WARNING_POP
{
// contains() must not throw for an empty reference token if the current
// value is an array (cf. #5395) -- at() still reports out_of_range.404
json j_nested = {{"a", {1, 2}}};
const json j_nested_const = j_nested;
json::json_pointer const jp("/a/");
std::string const throw_msg = "[json.exception.out_of_range.404] unresolved reference token ''";
CHECK_THROWS_WITH_AS(j_nested.at(jp), throw_msg.c_str(), json::out_of_range&);
CHECK_THROWS_WITH_AS(j_nested_const.at(jp), throw_msg.c_str(), json::out_of_range&);
CHECK(j_nested.contains(json::json_pointer("/a/1")));
CHECK(!j_nested.contains(jp));
CHECK(!j_nested_const.contains(jp));
// same for an empty reference token on a top-level array
CHECK(!j.contains(json::json_pointer("/")));
CHECK(!j_const.contains(json::json_pointer("/")));
}
CHECK_THROWS_WITH_AS(j.at("/one"_json_pointer) = 1,
"[json.exception.parse_error.109] parse error: array index 'one' is not a number", json::parse_error&);
CHECK_THROWS_WITH_AS(j_const.at("/one"_json_pointer) == 1,