|
| 1 | +#include <stdlib.h> |
1 | 2 | #include <sstream>
|
| 3 | +#include <fstream> |
| 4 | +#include <iostream> |
2 | 5 | #include <limits>
|
3 | 6 |
|
4 | 7 | #include "common/json.h"
|
@@ -36,4 +39,63 @@ void JSon::readJson(const string &jsonstr, vector<FieldValueTuple> &fv)
|
36 | 39 | }
|
37 | 40 | }
|
38 | 41 |
|
| 42 | +bool JSon::loadJsonFromFile(ifstream &fs, vector<KeyOpFieldsValuesTuple> &db_items) |
| 43 | +{ |
| 44 | + nlohmann::json json_array; |
| 45 | + fs >> json_array; |
| 46 | + |
| 47 | + if (!json_array.is_array()) |
| 48 | + { |
| 49 | + SWSS_LOG_ERROR("Root element must be an array."); |
| 50 | + return false; |
| 51 | + } |
| 52 | + |
| 53 | + for (size_t i = 0; i < json_array.size(); i++) |
| 54 | + { |
| 55 | + auto &arr_item = json_array[i]; |
| 56 | + |
| 57 | + if (arr_item.is_object()) |
| 58 | + { |
| 59 | + if (el_count != arr_item.size()) |
| 60 | + { |
| 61 | + SWSS_LOG_ERROR("Chlid elements must have both key and op entry. %s", |
| 62 | + arr_item.dump().c_str()); |
| 63 | + return false; |
| 64 | + } |
| 65 | + |
| 66 | + db_items.push_back(KeyOpFieldsValuesTuple()); |
| 67 | + auto &cur_db_item = db_items[db_items.size() - 1]; |
| 68 | + |
| 69 | + for (nlohmann::json::iterator child_it = arr_item.begin(); child_it != arr_item.end(); child_it++) { |
| 70 | + auto cur_obj_key = child_it.key(); |
| 71 | + auto &cur_obj = child_it.value(); |
| 72 | + |
| 73 | + if (cur_obj.is_object()) { |
| 74 | + kfvKey(cur_db_item) = cur_obj_key; |
| 75 | + for (nlohmann::json::iterator cur_obj_it = cur_obj.begin(); cur_obj_it != cur_obj.end(); cur_obj_it++) |
| 76 | + { |
| 77 | + string field_str = cur_obj_it.key(); |
| 78 | + string value_str; |
| 79 | + if ((*cur_obj_it).is_number()) |
| 80 | + value_str = to_string((*cur_obj_it).get<int>()); |
| 81 | + else if ((*cur_obj_it).is_string()) |
| 82 | + value_str = (*cur_obj_it).get<string>(); |
| 83 | + kfvFieldsValues(cur_db_item).push_back(FieldValueTuple(field_str, value_str)); |
| 84 | + } |
| 85 | + } |
| 86 | + else |
| 87 | + { |
| 88 | + kfvOp(cur_db_item) = cur_obj.get<string>(); |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | + else |
| 93 | + { |
| 94 | + SWSS_LOG_ERROR("Child elements must be objects. element:%s", arr_item.dump().c_str()); |
| 95 | + return false; |
| 96 | + } |
| 97 | + } |
| 98 | + return true; |
| 99 | +} |
| 100 | + |
39 | 101 | }
|
0 commit comments