From da25ac0d48e728cb424f1fce7f266563ec6f96b0 Mon Sep 17 00:00:00 2001 From: Luke Wilde Date: Sun, 10 Jul 2022 21:37:28 +0100 Subject: [PATCH] AK: Treat empty string as invalid JSON Previously we would treat the empty string as `null`. This caused JavaScript like this to fail: ```js var object = {}; try { object = JSON.parse(""); } catch {} var array = object.array || []; ``` Since `JSON.parse("")` returned null instead of throwing, it would set `object` to null and then try and use it instead of using the default backup value. --- AK/JsonValue.cpp | 2 -- Tests/AK/TestJSON.cpp | 2 +- Userland/Libraries/LibJS/Tests/builtins/JSON/JSON.parse.js | 1 + 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/AK/JsonValue.cpp b/AK/JsonValue.cpp index 9a6536b6196..f11fd4bc11d 100644 --- a/AK/JsonValue.cpp +++ b/AK/JsonValue.cpp @@ -236,8 +236,6 @@ void JsonValue::clear() #ifndef KERNEL ErrorOr JsonValue::from_string(StringView input) { - if (input.is_empty()) - return JsonValue(); return JsonParser(input).parse(); } #endif diff --git a/Tests/AK/TestJSON.cpp b/Tests/AK/TestJSON.cpp index 36f0b8cebc0..c55d21ed662 100644 --- a/Tests/AK/TestJSON.cpp +++ b/Tests/AK/TestJSON.cpp @@ -126,7 +126,7 @@ TEST_CASE(json_u64_roundtrip) TEST_CASE(json_parse_empty_string) { auto value = JsonValue::from_string(""); - EXPECT_EQ(value.value().is_null(), true); + EXPECT_EQ(value.is_error(), true); } TEST_CASE(json_parse_long_decimals) diff --git a/Userland/Libraries/LibJS/Tests/builtins/JSON/JSON.parse.js b/Userland/Libraries/LibJS/Tests/builtins/JSON/JSON.parse.js index a05e579e2a4..ff4d4bd30e2 100644 --- a/Userland/Libraries/LibJS/Tests/builtins/JSON/JSON.parse.js +++ b/Userland/Libraries/LibJS/Tests/builtins/JSON/JSON.parse.js @@ -29,6 +29,7 @@ test("syntax errors", () => { "[1,2,3, ]", '{ "foo": "bar",}', '{ "foo": "bar", }', + "", ].forEach(test => { expect(() => { JSON.parse(test);