Json: add typed safe-navigation member accessors

Value::has / get_str / get_num / get_bool / child_object / child_array —
convenience getters for walking dynamic JSON without manual find()+type-check
chains. Missing or wrong-typed keys yield the supplied default (scalars) or
nullptr (children); never throw. Tests in JsonAccessors.cpp.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 4.8 committed 2026-06-22 22:13:47 +03:00
1 parent adc0de310e
commit 44839f9f24
2 files changed
+96

No files matched your search

+50
View File
@@ -227,6 +227,56 @@ namespace Void::Json
return *p;
}
// ── typed member accessors (safe navigation) ──────────────────
// Convenience getters for walking dynamic JSON without manual
// find()+type-check chains. A missing key, or a present key of the
// wrong type, yields the supplied default (scalars) or nullptr
// (object/array children) — never throws.
[[nodiscard]] bool has(std::string_view key) const noexcept
{
return find(key) != nullptr;
}
[[nodiscard]] std::string
get_str(std::string_view key,
std::string_view fallback = {}) const
{
const Value* c = find(key);
return (c && c->is_string()) ? c->as_string()
: std::string{fallback};
}
[[nodiscard]] double get_num(std::string_view key,
double fallback = 0.0) const noexcept
{
const Value* c = find(key);
return (c && c->is_number()) ? c->as_number() : fallback;
}
[[nodiscard]] bool get_bool(std::string_view key,
bool fallback = false) const noexcept
{
const Value* c = find(key);
return (c && c->is_bool()) ? c->as_bool() : fallback;
}
// Child only when it exists and is an object; else nullptr.
[[nodiscard]] const Value*
child_object(std::string_view key) const noexcept
{
const Value* c = find(key);
return (c && c->is_object()) ? c : nullptr;
}
// Child only when it exists and is an array; else nullptr.
[[nodiscard]] const Value*
child_array(std::string_view key) const noexcept
{
const Value* c = find(key);
return (c && c->is_array()) ? c : nullptr;
}
// ── JSON Pointer (RFC 6901) query
// ───────────────────────────────────────── at("/a/b/0") walks
// object keys and array indices. Returns nullptr if any step is