Advertisement
Guest User

Untitled

a guest
Nov 19th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.14 KB | None | 0 0
  1. #include <iostream>
  2. #include <any>
  3. #include <vector>
  4. #include <sstream>
  5. #include <string>
  6. #include <fstream>
  7. #include <vector>
  8. #include <exception>
  9. #include <map>
  10. #include <list>
  11.  
  12. using namespace std;
  13.  
  14. class Json {
  15. any data;
  16. public:
  17.  
  18. // Конструктор из строки, содержащей Json-данные.
  19. Json(const std::string &s) {
  20. for (size_t i = 0; i < s.size(); i++) {
  21. if (s[i] == '{') {
  22. data = split_obj(s, i);
  23. } else {
  24. if (s[i] == '[') {
  25. data = split_arr(s, i);
  26. }
  27. else{
  28. throw std::logic_error("Error");
  29. }
  30. }
  31. }
  32. };
  33.  
  34. Json(const map<string, any> &map) {
  35. data = map;
  36. }
  37.  
  38. Json(const vector<any> &vector) {
  39. data = vector;
  40. }
  41.  
  42.  
  43. // Метод возвращает true, если данный экземпляр содержит в себе JSON-массив. Иначе false.
  44. bool is_array() const {
  45. try {
  46. any_cast<vector<any>>(data);
  47. return true;
  48. }
  49. catch (const bad_any_cast &e) {
  50. return false;
  51. }
  52. };
  53.  
  54. // Метод возвращает true, если данный экземпляр содержит в себе JSON-объект. Иначе false.
  55. bool is_object() const {
  56. try {
  57. any_cast<map<string, any>>(data);
  58. return true;
  59. }
  60. catch (const bad_any_cast &e) {
  61. return false;
  62. }
  63. };
  64.  
  65. // Метод возвращает значение по ключу key, если экземпляр является JSON-объектом.
  66. // Значение может иметь один из следующих типов: Json, std::string, double, bool или быть пустым.
  67. // Если экземпляр является JSON-массивом, генерируется исключение.
  68. std::any &operator[](const std::string &key) {
  69. try {
  70. if (is_object()) {
  71. //return data.key;
  72. }
  73. }
  74. catch (std::exception &e) {
  75. std::cout << e.what() << std::endl;
  76. }
  77.  
  78. };
  79.  
  80. // Метод возвращает значение по индексу index, если экземпляр является JSON-массивом.
  81. // Значение может иметь один из следующих типов: Json, std::string, double, bool или быть пустым.
  82. // Если экземпляр является JSON-объектом, генерируется исключение.
  83. std::any &operator[](int index) {
  84. try {
  85. if (is_array()) {
  86. //return data[index];
  87. }
  88. }
  89. catch (std::exception &e) {
  90. std::cout << e.what() << std::endl;
  91. }
  92. };
  93.  
  94. // Метод возвращает объект класса Json из строки, содержащей Json-данные.
  95. static Json parse(const std::string &s) {
  96. return Json(s);
  97. };
  98.  
  99. // Метод возвращает объекта класса Json из файла, содержащего Json-данные в текстовом формате.
  100. static Json parseFile(const std::string &path_to_file) {
  101. ifstream file;
  102. string s;
  103. string line;
  104. while (getline(file, line)) {
  105. s += line;
  106. }
  107. return Json(s);
  108. };
  109.  
  110. string split_string(const string &str, size_t &j) {
  111. string result;
  112. std::string::size_type next;
  113. j = str.find('"', j);
  114. if (str[j] == '"') {
  115. next = str.find('"', j++);
  116. result = str.substr(j++, next--);
  117. j = next++;
  118. } else {
  119. throw std::logic_error("Error");
  120. /*j = str.find('"', j++);
  121. next = str.find('"', j++);
  122. result = str.substr(j++, next--);
  123. j = next;*/
  124. }
  125. /*else if(str[j] == ':' || str[j] == ',') {
  126. throw std::logic_error("Error");
  127. }*/
  128. return result;
  129. }
  130.  
  131. bool split_bool(const string &str, size_t &j) {
  132. string string;
  133.  
  134. for (size_t i = j; i < str.size(); ++i)
  135. {
  136. if (isalpha(str[i])) {
  137. string += str[i];
  138. }
  139. else if (str[i] == ',' || str[i] == ']' || str[i] == '}') {
  140. j = --i;
  141. if (string == "false") {
  142. return false;
  143. }
  144. else if (string == "true") {
  145. return true;
  146. }
  147. else {
  148. throw std::invalid_argument("Wrong argument");
  149. }
  150. }
  151. else {
  152. throw std::invalid_argument("Error");
  153. }
  154. }
  155. return false;
  156. }
  157.  
  158. double split_double(const string &str, size_t &j) {
  159. string s;
  160. for (size_t i = j; i < str.find_first_not_of(isdigit(str[j])); ++i) {
  161. if (isdigit(str[i]) || str[i] == '.') {
  162. s += str[i];
  163. } else if (str[i] == ',' || str[i] == ']' || str[i] == '}'
  164. || isspace(str[i])) {
  165. j = --i;
  166. return stod(s);
  167. }
  168. else{
  169. throw std::logic_error("Error");
  170. }
  171. }
  172. }
  173.  
  174. vector<any> split_arr(const string &str, size_t &j) {
  175. vector<any> result;
  176. j = str.find('[', j);
  177. size_t next = j;
  178. size_t exit = str.find(']', j++);
  179. if (str[j] == '[')
  180. while (next < exit)
  181. for (size_t i = j; i < str.find_last_of(']', j++); i++) {
  182. next = str.find('[', next++);
  183. exit = str.find(']', exit++);
  184. }
  185.  
  186. if (str[j] == '[') {
  187. for (size_t i = j; i < exit; i++) {
  188. if (isdigit(str[i])) {
  189. result.emplace_back(split_double(str, i));
  190. i = j;
  191. } else if (isalpha(str[i])) {
  192. result.emplace_back(split_bool(str, i));
  193. i = j;
  194. } else if (str[i] == '"') {
  195. result.emplace_back(split_string(str, i));
  196. i = j;
  197. } else if (str[i] == '[') {
  198. result.emplace_back(Json(split_arr(str, i)));
  199. i = j;
  200. } else if (str[i] == '{') {
  201. result.emplace_back(Json(split_obj(str, i)));
  202. i = j;
  203. } else if (str[i] == ',') {
  204. i = str.find_first_not_of(isspace(str[i]), i++);
  205. i = j;
  206. } else if (str[i] == ']') {
  207. j = i;
  208. return result;
  209. }
  210. }
  211. }
  212. }
  213.  
  214. map<string, any> split_obj(const string &str, size_t &j) {
  215. map<string, any> result;
  216. string key;
  217. bool iskey = true;
  218. j = str.find('{', j);
  219. size_t next = j;
  220. size_t exit = str.find('}', j++);
  221. if (str[j] == '{')
  222. while (next < exit)
  223. for (size_t i = j; i < str.find_last_of('}', j++); i++) {
  224. next = str.find('{', next++);
  225. exit = str.find('}', exit++);
  226. }
  227.  
  228. if (str[j] == '{') {
  229. for (size_t i = j; i < exit; i++) {
  230. if (str[i] == '"' && iskey) {
  231. key = split_string(str, i);
  232. iskey = false;
  233. j = str.find(':', i);
  234. i = str.find_first_not_of(isspace(str[j]), j++);
  235. } else if (str[i] == '"' && !iskey) {
  236. result[key] = split_string(str, i);
  237. i = str.find('"', j);
  238. iskey = true;
  239. } else if (isdigit(str[i])) {
  240. result[key] = split_double(str, i);
  241. i = str.find('"', j);
  242. iskey = true;
  243. } else if (isalpha(str[i])) {
  244. result[key] = split_bool(str, i);
  245. i = str.find('"', j);
  246. iskey = true;
  247. } else if (str[i] == '[') {
  248. result[key] = split_arr(str, i);
  249. i = str.find('"', j);
  250. iskey = true;
  251. } else if (str[i] == '{') {
  252. result[key] = split_obj(str, i);
  253. i = str.find('"', j);
  254. iskey = true;
  255. } else if (str[i] == '}') {
  256. j = i;
  257. return result;
  258. }
  259. }
  260. }
  261. }
  262.  
  263. void print(any _data) {
  264. string type = _data.type().name();
  265.  
  266. try {
  267. if (type == "i") {
  268. cout << any_cast<int> (_data);
  269. }
  270. else if (type == "d") {
  271. cout << any_cast<double> (_data);
  272. }
  273. else if (type == "b") {
  274. if (any_cast<bool> (_data)) std::cout << "true";
  275. else cout << "false";
  276. }
  277. else if (type == "Ss" || type == "NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE") {
  278. cout << any_cast<string> (_data);
  279. }
  280. else if (type.find("St6vector") < type.length()) {
  281. std::vector <std::any> vec;
  282. vec = any_cast<vector<any>>(_data);
  283. unsigned int count = 0;
  284. cout << "[ ";
  285. for (const auto& c : vec) {
  286. count++;
  287. if (count > 1) std::cout << " , ";
  288. print(c);
  289. }
  290. cout << " ]";
  291. }
  292. else if (type.find("St3map") < type.length()) {
  293. map <string, any> _map;
  294. _map = std::any_cast<map <string, any>>(_data);
  295. cout << "{\n" ;
  296. unsigned int count = 0;
  297. for (const auto& c: _map) {
  298. count++;
  299. if (count > 1) cout << " ,\n";
  300. cout << "\t" << c.first << " : ";
  301. print(c.second);
  302. }
  303. cout << "\n\t}";
  304. }
  305. }
  306. catch(const std::bad_any_cast& e) {
  307. cout << e.what() << '\n';
  308. }
  309. }
  310.  
  311. void print_map() {
  312. cout << "{\n";
  313. int i = 0;
  314. for(const auto& p : any_cast<map<string, any>>(data)) {
  315. if (i != 0) cout <<",\n";
  316. cout << " "<< p.first << " : ";
  317. print(p.second);
  318. i++;
  319. }
  320. cout<< "}\n";
  321. }
  322.  
  323. };
  324.  
  325. int main() {
  326. string text;
  327. text = R"({ "lastname" : "Ivanov" , "firstname" : "Ivan" , "age" : 25,"islegal" : false,"marks" : [ 4 , 5 , 5 , 5 , 2 , 3 ],"address" : { "city" : "Moscow" , "street" : "Vozdvijenka" } })";
  328. Json object = Json::parse(text);
  329. cout<< endl;
  330. object.print_map();
  331.  
  332. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement