From ebd36ea92c448ad633cda970702280c872d72e39 Mon Sep 17 00:00:00 2001 From: Esma Date: Sun, 12 Nov 2023 16:16:48 +0100 Subject: [PATCH] added new function: getFormattedCommodities --- src/data.cpp | 45 +++++++++++++++++++++++++++++++++++++++++++++ src/include/data.h | 8 ++++++++ 2 files changed, 53 insertions(+) diff --git a/src/data.cpp b/src/data.cpp index 49fb528..8b8d3d6 100644 --- a/src/data.cpp +++ b/src/data.cpp @@ -559,4 +559,49 @@ std::string getFormattedMajorIndices(const std::string &pathToJson, const std::s } return getFormattedPrices(indicesSymbols, indicesNames, indicesDescriptions, markdown); +} + +std::string getFormattedCommodities(const std::string &pathToJson, bool markdown) +{ + // Load JSON data from a file + std::ifstream file(pathToJson); + if (!file.is_open()) { + return "Error: Unable to open JSON file."; + } + + // Read JSON data from the file + std::string jsonData((std::istreambuf_iterator(file)), std::istreambuf_iterator()); + file.close(); + + rapidjson::Document document; + document.Parse(jsonData.c_str()); + + if (!document.IsObject()) + { + return "Error: Invalid JSON data."; + } + + rapidjson::Value::ConstMemberIterator commodities = document.FindMember("commodities"); + if (commodities == document.MemberEnd() || !commodities->value.IsArray()) + { + return "Error: commodities data not found."; + } + + const rapidjson::Value &commoditiesData = commodities->value; + + std::vector symbols; + std::vector names; + + // Put data in vectors + for (rapidjson::SizeType i = 0; i < commoditiesData.Size(); ++i) + { + const rapidjson::Value &comData = commoditiesData[i]; + if (comData.HasMember("symbol") && comData.HasMember("name")) + { + symbols.push_back(comData["symbol"].GetString()); + names.push_back(comData["name"].GetString()); + } + } + + return getFormattedPrices(symbols, names, {}, markdown); } \ No newline at end of file diff --git a/src/include/data.h b/src/include/data.h index e208834..3014c29 100644 --- a/src/include/data.h +++ b/src/include/data.h @@ -124,4 +124,12 @@ std::string getFormattedPrices(std::vector indicesSymbols, std::vec /// @return A string with the formatted price data and descriptions. std::string getFormattedMajorIndices(const std::string &pathToJson, const std::string ®ion, bool description, bool markdown = false); +/// This function reads JSON data containing names and symbols of different commodities +/// from a JSON file. It extracts the symbols and names and formats the data +/// using Markdown syntax if requested. If an error occurs, it will return an error message. +/// @param pathToJson Path to the JSON file. +/// @param markdown When set to true, the formatted string will contain Markdown syntax to make it more visually appealing. +/// @return A string with the formatted price data. +std::string getFormattedCommodities(const std::string &pathToJson, bool markdown = false); + #endif // DATA_H \ No newline at end of file