Merge pull request #336 from totalgee/from_json_fix
Handle negative numbers in JSONParse::parse_number
This commit is contained in:
commit
468d65a661
@ -567,12 +567,17 @@ struct JSONParser {
|
|||||||
std::string val, exp_str;
|
std::string val, exp_str;
|
||||||
char c = '\0';
|
char c = '\0';
|
||||||
bool isDouble = false;
|
bool isDouble = false;
|
||||||
|
bool isNegative = false;
|
||||||
long exp = 0;
|
long exp = 0;
|
||||||
|
if( offset < str.size() && str[offset] == '-' ) {
|
||||||
|
isNegative = true;
|
||||||
|
++offset;
|
||||||
|
}
|
||||||
for (; offset < str.size() ;) {
|
for (; offset < str.size() ;) {
|
||||||
c = str[offset++];
|
c = str[offset++];
|
||||||
if( (c == '-') || (c >= '0' && c <= '9') ) {
|
if( c >= '0' && c <= '9' ) {
|
||||||
val += c;
|
val += c;
|
||||||
} else if( c == '.' ) {
|
} else if( c == '.' && !isDouble ) {
|
||||||
val += c;
|
val += c;
|
||||||
isDouble = true;
|
isDouble = true;
|
||||||
} else {
|
} else {
|
||||||
@ -608,12 +613,12 @@ struct JSONParser {
|
|||||||
--offset;
|
--offset;
|
||||||
|
|
||||||
if( isDouble ) {
|
if( isDouble ) {
|
||||||
return JSON(chaiscript::parse_num<double>( val ) * std::pow( 10, exp ));
|
return JSON((isNegative?-1:1) * chaiscript::parse_num<double>( val ) * std::pow( 10, exp ));
|
||||||
} else {
|
} else {
|
||||||
if( !exp_str.empty() ) {
|
if( !exp_str.empty() ) {
|
||||||
return JSON(static_cast<double>(chaiscript::parse_num<long>( val )) * std::pow( 10, exp ));
|
return JSON((isNegative?-1:1) * static_cast<double>(chaiscript::parse_num<long>( val )) * std::pow( 10, exp ));
|
||||||
} else {
|
} else {
|
||||||
return JSON(chaiscript::parse_num<long>( val ));
|
return JSON((isNegative?-1:1) * chaiscript::parse_num<long>( val ));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1 +1,2 @@
|
|||||||
assert_equal(from_json("100"), 100)
|
assert_equal(from_json("100"), 100)
|
||||||
|
assert_equal(from_json("-100"), -100)
|
||||||
|
@ -1 +1,22 @@
|
|||||||
assert_equal(from_json("1.234"), 1.234)
|
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);
|
||||||
|
@ -1,2 +1,2 @@
|
|||||||
assert_equal(from_json("[1,2,3]"), [1,2,3])
|
assert_equal(from_json("[1,-2,3]"), [1,-2,3])
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user