From 45f732b84f04b8c44c2e47900ae1291ae76a5206 Mon Sep 17 00:00:00 2001 From: IgnoreWarnings Date: Tue, 11 Jun 2024 11:27:30 +0000 Subject: [PATCH] add json class Signed-off-by: IgnoreWarnings --- fpga/include/villas/fpga/json_parser.hpp | 54 ++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 fpga/include/villas/fpga/json_parser.hpp diff --git a/fpga/include/villas/fpga/json_parser.hpp b/fpga/include/villas/fpga/json_parser.hpp new file mode 100644 index 000000000..3e389a80c --- /dev/null +++ b/fpga/include/villas/fpga/json_parser.hpp @@ -0,0 +1,54 @@ +/* Wrapper for Jannson library to process Json files in OOP. + * + * Author: Pascal Bauer + * + * SPDX-FileCopyrightText: 2023-2024 Pascal Bauer + * SPDX-License-Identifier: Apache-2.0 + */ + +#pragma once + +#include +#include +#include +#include + + +class JsonParser { +private: + inline static auto logger = villas::logging.get("Json Parser"); + +public: + json_t* json; + +public: + JsonParser(json_t *json) : json(json) {} + + JsonParser(const std::string &configFilePath) { + FILE *f = fopen(configFilePath.c_str(), "r"); + if (!f) + throw RuntimeError("Cannot open config file: {}", configFilePath); + + this->json = json_loadf(f, 0, nullptr); + if (!json) { + logger->error("Cannot parse JSON config"); + fclose(f); + throw RuntimeError("Cannot parse JSON config"); + } + + fclose(f); + } + + ~JsonParser() { + json_decref(json); + } + + json_t* get(const std::string &key) { + json_t* result = json_object_get(this->json, key.c_str()); + if (result == nullptr) { + logger->error("No section {} found in config", key); + exit(1); + } + return result; + } +}; \ No newline at end of file