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\"}";