From b1ab5056084279e8ea9d70a0a3e1ce1ef1eb159d Mon Sep 17 00:00:00 2001 From: rida Date: Fri, 27 Nov 2026 03:49:56 +0200 Subject: [PATCH] fix: parse JSON data with leading whitespace JSONParser wrapped any string that did not start with [, { or " in quotes before calling JSON.parse. A JSON body starting with a newline or spaces was therefore treated as a string and threw on the newline, and bare strings containing quotes or line breaks threw too. Check the first non-whitespace character and quote bare strings with JSON.stringify. Signed-off-by: rida --- src/parsers.ts | 6 ++++-- test/integration/parser_test.ts | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/parsers.ts b/src/parsers.ts index 7a050672..40f1656a 100644 --- a/src/parsers.ts +++ b/src/parsers.ts @@ -28,8 +28,10 @@ export class JSONParser implements Parser { // This is kind of a hack, but the payload data could be JSON in the form of a single // string, such as "some data". But without the quotes in the string, JSON.parse blows // up. We can check for this scenario and add quotes. Not sure if this is ideal. - if (!/^[[|{|"]/.test(payload)) { - payload = `"${payload}"`; + // Leading whitespace is allowed before JSON, so it must not turn an object or an array + // into a string. JSON.stringify quotes the string safely when it contains quotes or line breaks. + if (!/^[[{"]/.test(payload.trimStart())) { + payload = JSON.stringify(payload); } } if (this.decorator) { diff --git a/test/integration/parser_test.ts b/test/integration/parser_test.ts index 5be19b3e..ba6fb6ef 100644 --- a/test/integration/parser_test.ts +++ b/test/integration/parser_test.ts @@ -67,6 +67,30 @@ describe("JSON Event Format Parser", () => { expect(parser.parse(payload)).to.equal("I am a string!"); }); + it("Accepts a string containing double quotes", () => { + const parser = new Parser(); + + expect(parser.parse("She said \"hi\"")).to.equal("She said \"hi\""); + }); + + it("Accepts a string containing line breaks", () => { + const parser = new Parser(); + + expect(parser.parse("line 1\nline 2\r\n")).to.equal("line 1\nline 2\r\n"); + }); + + it("Must parse a JSON object with leading whitespace", () => { + const parser = new Parser(); + + expect(parser.parse("\n {\"much\" : \"wow\"}")).to.deep.equal({ much: "wow" }); + }); + + it("Must parse a JSON array with leading whitespace", () => { + const parser = new Parser(); + + expect(parser.parse(" [1, 2]")).to.deep.equal([1, 2]); + }); + it("Must accept when the payload is a string well formed as JSON", () => { // setup const payload = "{\"much\" : \"wow\"}";