diff --git a/include/chaiscript/utility/json.hpp b/include/chaiscript/utility/json.hpp index 96decc0..676b469 100644 --- a/include/chaiscript/utility/json.hpp +++ b/include/chaiscript/utility/json.hpp @@ -567,12 +567,17 @@ struct JSONParser { std::string val, exp_str; char c = '\0'; bool isDouble = false; + bool isNegative = false; long exp = 0; + if( offset < str.size() && str[offset] == '-' ) { + isNegative = true; + ++offset; + } for (; offset < str.size() ;) { c = str[offset++]; - if( (c == '-') || (c >= '0' && c <= '9') ) { + if( c >= '0' && c <= '9' ) { val += c; - } else if( c == '.' ) { + } else if( c == '.' && !isDouble ) { val += c; isDouble = true; } else { @@ -608,12 +613,12 @@ struct JSONParser { --offset; if( isDouble ) { - return JSON(chaiscript::parse_num( val ) * std::pow( 10, exp )); + return JSON((isNegative?-1:1) * chaiscript::parse_num( val ) * std::pow( 10, exp )); } else { if( !exp_str.empty() ) { - return JSON(static_cast(chaiscript::parse_num( val )) * std::pow( 10, exp )); + return JSON((isNegative?-1:1) * static_cast(chaiscript::parse_num( val )) * std::pow( 10, exp )); } else { - return JSON(chaiscript::parse_num( val )); + return JSON((isNegative?-1:1) * chaiscript::parse_num( val )); } } } diff --git a/unittests/json_3.chai b/unittests/json_3.chai index d3f222e..11ce7dc 100644 --- a/unittests/json_3.chai +++ b/unittests/json_3.chai @@ -1 +1,2 @@ assert_equal(from_json("100"), 100) +assert_equal(from_json("-100"), -100) diff --git a/unittests/json_4.chai b/unittests/json_4.chai index 22d388c..ae07024 100644 --- a/unittests/json_4.chai +++ b/unittests/json_4.chai @@ -1 +1,22 @@ assert_equal(from_json("1.234"), 1.234) +assert_equal(from_json("-1.234"), -1.234) + +auto caught = false; +try { + from_json("-1-5.3"); +} +catch(e) { + assert_equal("JSON ERROR: Number: unexpected character '-'", e.what()); + caught = true; +} +assert_equal(caught, true); + +caught = false; +try { + from_json("-15.3.2"); +} +catch(e) { + assert_equal("JSON ERROR: Number: unexpected character '.'", e.what()); + caught = true; +} +assert_equal(caught, true); diff --git a/unittests/json_9.chai b/unittests/json_9.chai index 1512738..d8c6423 100644 --- a/unittests/json_9.chai +++ b/unittests/json_9.chai @@ -1,2 +1,2 @@ -assert_equal(from_json("[1,2,3]"), [1,2,3]) +assert_equal(from_json("[1,-2,3]"), [1,-2,3])