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:
1 parent
adc0de310e
commit
44839f9f24
2 files changed
+96
No files matched your search
@@ -0,0 +1,46 @@
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
using Void::Json::parse;
|
||||
|
||||
// Typed safe-navigation member accessors on Json::Value.
|
||||
|
||||
Void::Testing::Test json_accessors_present()
|
||||
{
|
||||
const auto v =
|
||||
parse("{\"s\":\"hi\",\"n\":42,\"b\":true,\"o\":{\"x\":1},\"a\":[1,2]}");
|
||||
Void::Testing::expect(v.has_value());
|
||||
Void::Testing::expect(v->has("s"));
|
||||
Void::Testing::expect_eq(v->get_str("s"), std::string{"hi"});
|
||||
Void::Testing::expect_eq(v->get_num("n"), 42.0);
|
||||
Void::Testing::expect(v->get_bool("b"));
|
||||
Void::Testing::expect(v->child_object("o") != nullptr);
|
||||
Void::Testing::expect(v->child_array("a") != nullptr);
|
||||
}
|
||||
|
||||
Void::Testing::Test json_accessors_missing_and_wrong_type()
|
||||
{
|
||||
const auto v = parse("{\"s\":\"hi\",\"n\":42}");
|
||||
Void::Testing::expect(v.has_value());
|
||||
Void::Testing::expect(!v->has("nope"));
|
||||
Void::Testing::expect_eq(v->get_str("nope", "def"), std::string{"def"});
|
||||
Void::Testing::expect_eq(v->get_num("nope", -1.0), -1.0);
|
||||
Void::Testing::expect(!v->get_bool("nope"));
|
||||
Void::Testing::expect(v->child_object("nope") == nullptr);
|
||||
Void::Testing::expect(v->child_array("nope") == nullptr);
|
||||
// Wrong type → fallback / nullptr.
|
||||
Void::Testing::expect_eq(v->get_str("n", "x"), std::string{"x"});
|
||||
Void::Testing::expect(v->child_object("s") == nullptr);
|
||||
Void::Testing::expect(v->child_array("n") == nullptr);
|
||||
}
|
||||
|
||||
Void::Testing::Test json_accessors_on_non_object()
|
||||
{
|
||||
const auto v = parse("[1,2,3]");
|
||||
Void::Testing::expect(v.has_value());
|
||||
Void::Testing::expect(!v->has("k"));
|
||||
Void::Testing::expect_eq(v->get_str("k", "d"), std::string{"d"});
|
||||
}
|
||||
Reference in new issue
Block a user