// // json_common.h // json // // Created by Sam Jaffe on 4/22/16. // #pragma once #include #include #include namespace json { class malformed_json_exception : public std::domain_error { using std::domain_error::domain_error; }; } namespace json { namespace helper { const char get_next_element(char const*& data) { while (isspace(*data)) ++data; return *data; } template void advance_to_boundary(char const*& data) { switch (get_next_element(data)) { case ',': // This is there 'more data remains' token for the compound value ++data; break; case E: // This is the end-token for the compound value break; default: // Error, malformed JSON throw json::malformed_json_exception(std::string("Expected to recieve container delimiter ',' or '") + E + "', got '" + *data + "' instead"); break; } } template void parse_string(T& json, char const*& data) { char const* start = data; while (*++data) { if (*data == '"' && *(data-1) != '\\') { json = std::string(start+1, data); ++data; return; } } throw json::malformed_json_exception("Could not locate end of string"); } template void parse_numeric(T& json, char const*& data) { // TODO: more sophisticated float detection? char const* start = data; while (*++data) { if (*data == '.') { while (isnumber(*++data)); json = atof(start); break; } else if (!isnumber(*data)) { json = atoi(start); break; } } } } }