Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- struct JSON {
- int value;
- std::vector<JSON> arr;
- bool isArray = false;
- };
- int parse_number(std::string &input, std::stack<JSON*> & stack, size_t &position) {
- char *end;
- char *start = input.c_str() + position;
- long result = std::strtol(start, &end, 10);
- if (errno == ERANGE || result > INT_MAX) {
- throw std::runtime_error("");
- }
- position += end - start;
- return result;
- }
- JSON parse_object(std::string &input, size_t &position) {
- switch(input[position]) {
- case('['):
- return parse_array(input, position);
- break;
- case('0'):
- case('1'):
- case('2'):
- case('3'):
- case('4'):
- case('5'):
- case('6'):
- case('7'):
- case('8'):
- case('9'):
- JSON result;
- result.value = parse_number(input, position);
- return result;
- default:
- throw std::runtime_error("muhahah");
- }
- ///unreachable
- return JSON();
- }
- JSON parse_array(std::string &input, size_t &position) {
- JSON result;
- result.is_array = true;
- position++;
- for(;;) {
- result.arr.emplace_back(parse_object(input,position));
- switch(input[position]) {
- case(','):
- position++;
- continue;
- case(']'):
- position++;
- return result;
- default:
- throw std::runtime_error();
- }
- }
- // unreachable
- return result;
- }
- JSON parse_json(std::string &input) {
- if (input.empty())
- throw std::runtime_error("");
- size_t position = 0;
- auto result = parse_object(input, position);
- if (position != input.size())
- throw std::runtime_error("");
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement