73 lines
2.4 KiB
C++
73 lines
2.4 KiB
C++
#pragma once
|
|
|
|
// Tolerant JSON readers and small builders used by every parser and request
|
|
// builder in this module. Missing or mistyped members read as the fallback;
|
|
// nothing here throws.
|
|
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
#include "clients/body/json.h"
|
|
|
|
namespace molo::meta {
|
|
|
|
using Json = clients::body::Json;
|
|
|
|
struct JsonX {
|
|
static const Json* member(const Json& doc, const std::string& key) {
|
|
return doc.is_object() ? doc.find(key) : nullptr;
|
|
}
|
|
static std::string str(const Json& doc, const std::string& key, const std::string& fb = "") {
|
|
const Json* v = member(doc, key);
|
|
return v && v->is_string() ? v->as_string() : fb;
|
|
}
|
|
static long num(const Json& doc, const std::string& key, long fb = 0) {
|
|
const Json* v = member(doc, key);
|
|
return v && v->is_number() ? v->as_int() : fb;
|
|
}
|
|
static double real(const Json& doc, const std::string& key, double fb = 0) {
|
|
const Json* v = member(doc, key);
|
|
return v && v->is_number() ? v->as_number() : fb;
|
|
}
|
|
static bool flag(const Json& doc, const std::string& key, bool fb = false) {
|
|
const Json* v = member(doc, key);
|
|
return v && v->is_bool() ? v->as_bool() : fb;
|
|
}
|
|
static const Json* obj(const Json& doc, const std::string& key) {
|
|
const Json* v = member(doc, key);
|
|
return v && v->is_object() ? v : nullptr;
|
|
}
|
|
static const Json* arr(const Json& doc, const std::string& key) {
|
|
const Json* v = member(doc, key);
|
|
return v && v->is_array() ? v : nullptr;
|
|
}
|
|
// Dotted path read: "usage.input_tokens_details.cached_tokens".
|
|
static long path_num(const Json& doc, const std::string& path, long fb = 0) {
|
|
const Json* cur = &doc;
|
|
std::size_t start = 0;
|
|
while (true) {
|
|
std::size_t dot = path.find('.', start);
|
|
std::string part = path.substr(start, dot == std::string::npos ? dot : dot - start);
|
|
cur = member(*cur, part);
|
|
if (!cur) return fb;
|
|
if (dot == std::string::npos) break;
|
|
start = dot + 1;
|
|
}
|
|
return cur->is_number() ? cur->as_int() : fb;
|
|
}
|
|
static Json strings(const std::vector<std::string>& v) {
|
|
Json a = Json::array();
|
|
for (const std::string& s : v) a.push(Json(s));
|
|
return a;
|
|
}
|
|
static void set_if(Json& obj, const char* key, const std::string& value) {
|
|
if (!value.empty()) obj.set(key, Json(value));
|
|
}
|
|
static void merge(Json& into, const Json& extra) {
|
|
if (!extra.is_object()) return;
|
|
for (const auto& [k, v] : extra.as_object()) into.set(k, v);
|
|
}
|
|
};
|
|
|
|
} // namespace molo::meta
|