| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- //
- // json_common.h
- // json
- //
- // Created by Sam Jaffe on 4/22/16.
- //
- #pragma once
- #include <cstdlib>
- #include <stdexcept>
- #include <string>
- 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 <char const E>
- 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 <typename T>
- 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 <typename T>
- 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;
- }
- }
- }
-
- }
- }
|