Add loadJSONFromFile() in utility
It provides a util function to load json from a file.
Tested: Manually verify the function works.
Signed-off-by: Lei YU <mine260309@gmail.com>
Change-Id: I4dc946663e0ce1bf511de90b27b7aa425a338543
diff --git a/utility.cpp b/utility.cpp
index 836bd33..214d8a9 100644
--- a/utility.cpp
+++ b/utility.cpp
@@ -15,6 +15,8 @@
*/
#include "utility.hpp"
+#include <fstream>
+
namespace witherspoon
{
namespace power
@@ -27,6 +29,7 @@
constexpr auto MAPPER_INTERFACE = "xyz.openbmc_project.ObjectMapper";
using namespace phosphor::logging;
+using json = nlohmann::json;
std::string getService(const std::string& path, const std::string& interface,
sdbusplus::bus::bus& bus)
@@ -53,6 +56,23 @@
return response.begin()->first;
}
+json loadJSONFromFile(const char* path)
+{
+ std::ifstream ifs(path);
+ if (!ifs.good())
+ {
+ log<level::ERR>("Unable to open file", entry("PATH=%s", path));
+ return nullptr;
+ }
+ auto data = json::parse(ifs, nullptr, false);
+ if (data.is_discarded())
+ {
+ log<level::ERR>("Failed to parse json", entry("PATH=%s", path));
+ return nullptr;
+ }
+ return data;
+}
+
} // namespace util
} // namespace power
} // namespace witherspoon
diff --git a/utility.hpp b/utility.hpp
index 0f008e3..df66852 100644
--- a/utility.hpp
+++ b/utility.hpp
@@ -1,5 +1,6 @@
#pragma once
+#include <nlohmann/json.hpp>
#include <phosphor-logging/elog.hpp>
#include <phosphor-logging/log.hpp>
#include <sdbusplus/bus.hpp>
@@ -104,6 +105,15 @@
bus.call_noreply(method);
}
+/**
+ * Load json from a file
+ *
+ * @param[in] path - The path of the json file
+ *
+ * @return The nlohmann::json object
+ */
+nlohmann::json loadJSONFromFile(const char* path);
+
} // namespace util
} // namespace power
} // namespace witherspoon