src: be more forgiving parsing JSON as a string (#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 <lball@redhat.com>
This commit is contained in:
parent
e06147b9de
commit
db4be6b1da
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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", () => {
|
||||
|
|
Loading…
Reference in New Issue