Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/parsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
24 changes: 24 additions & 0 deletions test/integration/parser_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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\"}";
Expand Down
Loading