JKSV/include/JSON.hpp

37 lines
1.3 KiB
C++

#pragma once
#include <json-c/json.h>
#include <memory>
#include <string>
namespace json
{
// Use this instead of default json_object
using Object = std::unique_ptr<json_object, decltype(&json_object_put)>;
// Use this instead of json_object_from_x. Pass the function and its arguments instead.
template <typename... Args>
static inline json::Object new_object(json_object *(*function)(Args...), Args... args)
{
return json::Object((*function)(args...), json_object_put);
}
/// @brief Inline wrapper function for getting a json object by it's key.
/// @param json json::Object to get the key from.
/// @param key Key to get.
/// @return json_object on success. NULL on failure.
static inline json_object *get_object(json::Object &json, std::string_view key)
{
return json_object_object_get(json.get(), key.data());
}
/// @brief Inline wrapper function to add an object to a json_object
/// @param json Json object to add an object to.
/// @param key Key of the object.
/// @param object Object to add to json.
/// @return True on success. False on failure.
static inline bool add_object(json::Object &json, std::string_view key, json_object *object)
{
return json_object_object_add(json.get(), key.data(), object) == 0;
}
} // namespace json