From 75f9d45c1e52a805db071ff9f09e44558968bbbe Mon Sep 17 00:00:00 2001 From: Stephen Sun Date: Tue, 2 Jun 2020 02:45:02 +0000 Subject: [PATCH] [json] Port json parser from swssconfig to swss-common so that other component can take advantage of this tool --- common/json.cpp | 62 +++++++++++++++++++++++++++++++++++++++++++++++++ common/json.h | 8 +++++-- 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/common/json.cpp b/common/json.cpp index dd0c5e9f8..d1d4f7149 100644 --- a/common/json.cpp +++ b/common/json.cpp @@ -1,4 +1,7 @@ +#include #include +#include +#include #include #include "common/json.h" @@ -36,4 +39,63 @@ void JSon::readJson(const string &jsonstr, vector &fv) } } +bool JSon::loadJsonFromFile(ifstream &fs, vector &db_items) +{ + nlohmann::json json_array; + fs >> json_array; + + if (!json_array.is_array()) + { + SWSS_LOG_ERROR("Root element must be an array."); + return false; + } + + for (size_t i = 0; i < json_array.size(); i++) + { + auto &arr_item = json_array[i]; + + if (arr_item.is_object()) + { + if (el_count != arr_item.size()) + { + SWSS_LOG_ERROR("Chlid elements must have both key and op entry. %s", + arr_item.dump().c_str()); + return false; + } + + db_items.push_back(KeyOpFieldsValuesTuple()); + auto &cur_db_item = db_items[db_items.size() - 1]; + + for (nlohmann::json::iterator child_it = arr_item.begin(); child_it != arr_item.end(); child_it++) { + auto cur_obj_key = child_it.key(); + auto &cur_obj = child_it.value(); + + if (cur_obj.is_object()) { + kfvKey(cur_db_item) = cur_obj_key; + for (nlohmann::json::iterator cur_obj_it = cur_obj.begin(); cur_obj_it != cur_obj.end(); cur_obj_it++) + { + string field_str = cur_obj_it.key(); + string value_str; + if ((*cur_obj_it).is_number()) + value_str = to_string((*cur_obj_it).get()); + else if ((*cur_obj_it).is_string()) + value_str = (*cur_obj_it).get(); + kfvFieldsValues(cur_db_item).push_back(FieldValueTuple(field_str, value_str)); + } + } + else + { + kfvOp(cur_db_item) = cur_obj.get(); + } + } + } + else + { + SWSS_LOG_ERROR("Child elements must be objects. element:%s", arr_item.dump().c_str()); + return false; + } + } + return true; +} + } diff --git a/common/json.h b/common/json.h index ecd5d1520..da7798fd4 100644 --- a/common/json.h +++ b/common/json.h @@ -2,6 +2,7 @@ #define __JSON__ #include +#include #include #include "table.h" @@ -10,9 +11,12 @@ namespace swss { class JSon { +private: + static const int el_count = 2; public: - static std::string buildJson(const std::vector &fv); - static void readJson(const std::string &json, std::vector &fv); + static std::string buildJson(const std::vector &fv); + static void readJson(const std::string &json, std::vector &fv); + static bool loadJsonFromFile(std::ifstream &fs, std::vector &db_items); }; }