Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. struct JSON {
  2. int value;
  3. std::vector<JSON> arr;
  4. bool isArray = false;
  5. };
  6.  
  7. int parse_number(std::string &input, std::stack<JSON*> & stack, size_t &position) {
  8. char *end;
  9. char *start = input.c_str() + position;
  10. long result = std::strtol(start, &end, 10);
  11. if (errno == ERANGE || result > INT_MAX) {
  12. throw std::runtime_error("");
  13. }
  14. position += end - start;
  15. return result;
  16. }
  17.  
  18. JSON parse_object(std::string &input, size_t &position) {
  19. switch(input[position]) {
  20. case('['):
  21. return parse_array(input, position);
  22. break;
  23. case('0'):
  24. case('1'):
  25. case('2'):
  26. case('3'):
  27. case('4'):
  28. case('5'):
  29. case('6'):
  30. case('7'):
  31. case('8'):
  32. case('9'):
  33. JSON result;
  34. result.value = parse_number(input, position);
  35. return result;
  36. default:
  37. throw std::runtime_error("muhahah");
  38. }
  39. ///unreachable
  40. return JSON();
  41. }
  42.  
  43. JSON parse_array(std::string &input, size_t &position) {
  44. JSON result;
  45. result.is_array = true;
  46. position++;
  47. for(;;) {
  48. result.arr.emplace_back(parse_object(input,position));
  49. switch(input[position]) {
  50. case(','):
  51. position++;
  52. continue;
  53. case(']'):
  54. position++;
  55. return result;
  56. default:
  57. throw std::runtime_error();
  58. }
  59. }
  60. // unreachable
  61. return result;
  62. }
  63.  
  64. JSON parse_json(std::string &input) {
  65. if (input.empty())
  66. throw std::runtime_error("");
  67. size_t position = 0;
  68. auto result = parse_object(input, position);
  69. if (position != input.size())
  70. throw std::runtime_error("");
  71. return result;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement