21namespace neograph::llm {
23using json = neograph::json;
28inline std::vector<std::string>
split_path(
const std::string& path) {
29 std::vector<std::string> segments;
30 if (path.empty())
return segments;
32 std::string::size_type start = 0;
33 while (start < path.size()) {
34 auto dot = path.find(
'.', start);
35 if (dot == std::string::npos) {
36 segments.push_back(path.substr(start));
39 segments.push_back(path.substr(start, dot - start));
47 if (s.empty())
return false;
49 if (c <
'0' || c >
'9')
return false;
55inline std::optional<json>
at_path(
const json& root,
const std::string& path) {
56 if (path.empty())
return root;
61 for (
const auto& seg : segments) {
62 if (current.is_object()) {
63 if (!current.contains(seg))
return std::nullopt;
64 current = current[seg];
65 }
else if (current.is_array() &&
is_index(seg)) {
66 size_t idx = std::stoul(seg);
67 if (idx >= current.size())
return std::nullopt;
68 current = current[idx];
77inline bool has_path(
const json& root,
const std::string& path) {
78 return at_path(root, path).has_value();
83inline T
get_path(
const json& root,
const std::string& path,
const T& default_val) {
84 auto node =
at_path(root, path);
85 if (!node)
return default_val;
87 return node->template get<T>();
97inline void set_path_walk(json parent,
const std::vector<std::string>& segs,
98 size_t i,
const json& value) {
99 if (i + 1 == segs.size()) {
100 parent[segs[i]] = value;
103 set_path_walk(parent[segs[i]], segs, i + 1, value);
108inline void set_path(json& root,
const std::string& path,
const json& value) {
114 if (segments.size() == 1) {
115 root[segments[0]] = value;
118 detail::set_path_walk(root[segments[0]], segments, 1, value);
Thin C++ RAII wrapper around yyjson with nlohmann-compatible API.
bool has_path(const json &root, const std::string &path)
True if path exists in root.
std::vector< std::string > split_path(const std::string &path)
Split "a.b.0.c" into ["a","b","0","c"].
void set_path(json &root, const std::string &path, const json &value)
Set value at path, creating intermediate objects as needed.
bool is_index(const std::string &s)
True if every char is a digit.
std::optional< json > at_path(const json &root, const std::string &path)
Navigate into root by dot-path. Returns nullopt if path doesn't resolve.
T get_path(const json &root, const std::string &path, const T &default_val)
Fetch value at path or return default_val on missing/wrong-type.