Skip to content

src: be more forgiving parsing JSON as a string #417

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 13, 2021
Merged
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
9 changes: 0 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions src/parsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ export class JSONParser implements Parser {
* @return {object} the parsed JSON payload.
*/
parse(payload: Record<string, unknown> | string): string {
if (typeof payload === "string") {
// 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}"`;
}
}
if (this.decorator) {
payload = this.decorator.parse(payload);
}
Expand Down
12 changes: 10 additions & 2 deletions test/integration/parser_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,19 @@ describe("JSON Event Format Parser", () => {

it("Throw error when payload is an invalid JSON", () => {
// setup
const payload = "gg";
const payload = "{gg";
const parser = new Parser();

// TODO: Should the parser catch the SyntaxError and re-throw a ValidationError?
expect(parser.parse.bind(parser, payload)).to.throw(SyntaxError, "Unexpected token g in JSON at position 0");
expect(parser.parse.bind(parser, payload)).to.throw(SyntaxError, "Unexpected token g in JSON at position 1");
});

it("Accepts a string as valid JSON", () => {
// setup
const payload = "I am a string!";
const parser = new Parser();

expect(parser.parse(payload)).to.equal("I am a string!");
});

it("Must accept when the payload is a string well formed as JSON", () => {
Expand Down