diff --git a/lib/aria/json/parser.aria b/lib/aria/json/parser.aria index 1c41224..b492941 100644 --- a/lib/aria/json/parser.aria +++ b/lib/aria/json/parser.aria @@ -81,7 +81,7 @@ func parse_value(stream) { } elsif c == 'n' { return parse_null(stream)?; } elsif c.is_digit() || c == '-' { - return JsonValue::Number(parse_number(stream))?; + return JsonValue::Number(parse_number(stream)?); } else { return json_err("Not a valid JSON value: " + c); } @@ -145,6 +145,27 @@ func parse_number(stream) { } } + # Handle scientific notation + if stream.peek() == 'e' || stream.peek() == 'E' { + text += stream.next(); + + if stream.peek() == '+' || stream.peek() == '-' { + text += stream.next(); + } + + # Check for Maybe::None first! + while true { + val c = stream.peek(); + if c == Maybe::None { + break; + } elsif c.is_digit() { + text += stream.next(); + } else { + break; + } + } + } + return Float.parse(text)?; } diff --git a/tests/json_scientific_notation.aria b/tests/json_scientific_notation.aria new file mode 100644 index 0000000..537ab8e --- /dev/null +++ b/tests/json_scientific_notation.aria @@ -0,0 +1,41 @@ +# SPDX-License-Identifier: Apache-2.0 + +### TAGS: XFAIL + +import JsonValue from aria.json.parser; +import aria.json.parser; + + +func main() { + val basic_result = JsonValue.parse("1e3")!!.flatten().unwrap_Number(); + assert basic_result == 1000.0; + + val lower_e_result = JsonValue.parse("2e2")!!.flatten(); + assert lower_e_result == 200.0; + + val upper_e_result = JsonValue.parse("3E2")!!.flatten(); + assert upper_e_result == 300.0; + + val negative_e_result = JsonValue.parse("5e-2")!!.flatten(); + assert negative_e_result == 0.05; + + val plus_sign_result = JsonValue.parse("4e+3")!!.flatten(); + assert plus_sign_result == 4000.0; + + val decimal_result = JsonValue.parse("1.5e2")!!.flatten(); + assert decimal_result == 150.0; + + val decimal_negative_result = JsonValue.parse("2.5e-3")!!.flatten(); + assert decimal_negative_result == 0.0025; + + val large_e_result = JsonValue.parse("1e10")!!.flatten(); + assert result8 == 10000000000.0; + + val arr = JsonValue.parse("[1e3, 2e-2, 3.5e1]")!!.flatten(); + assert arr[0] == 1000.0; + assert arr[1] == 0.02; + assert arr[2] == 35.0; + + val obj = JsonValue.parse('{"value": 1e3}')!!.flatten(); + assert obj["value"] == 1000.0; +} \ No newline at end of file