Skip to content

Commit db4be6b

Browse files
authored
src: be more forgiving parsing JSON as a string (cloudevents#417)
* src: be more forgiving parsing JSON as a string A simple string is considered valid JSON. However, our parsers do not accept that unless the string has quotation marks. This commit modifies the parser to look for strings declared as application/json which do not begin with '[' '{' or '"' and surrounds them with quotes. Signed-off-by: Lance Ball <[email protected]>
1 parent e06147b commit db4be6b

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

src/parsers.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,14 @@ export class JSONParser implements Parser {
1717
* @return {object} the parsed JSON payload.
1818
*/
1919
parse(payload: Record<string, unknown> | string): string {
20+
if (typeof payload === "string") {
21+
// This is kind of a hack, but the payload data could be JSON in the form of a single
22+
// string, such as "some data". But without the quotes in the string, JSON.parse blows
23+
// up. We can check for this scenario and add quotes. Not sure if this is ideal.
24+
if (!/^[[|{|"]/.test(payload)) {
25+
payload = `"${payload}"`;
26+
}
27+
}
2028
if (this.decorator) {
2129
payload = this.decorator.parse(payload);
2230
}

test/integration/parser_test.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,19 @@ describe("JSON Event Format Parser", () => {
4747

4848
it("Throw error when payload is an invalid JSON", () => {
4949
// setup
50-
const payload = "gg";
50+
const payload = "{gg";
5151
const parser = new Parser();
5252

5353
// TODO: Should the parser catch the SyntaxError and re-throw a ValidationError?
54-
expect(parser.parse.bind(parser, payload)).to.throw(SyntaxError, "Unexpected token g in JSON at position 0");
54+
expect(parser.parse.bind(parser, payload)).to.throw(SyntaxError, "Unexpected token g in JSON at position 1");
55+
});
56+
57+
it("Accepts a string as valid JSON", () => {
58+
// setup
59+
const payload = "I am a string!";
60+
const parser = new Parser();
61+
62+
expect(parser.parse(payload)).to.equal("I am a string!");
5563
});
5664

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

0 commit comments

Comments
 (0)