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
28 changes: 28 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vitest";
import { MalformedJSON, parse } from "./index";

describe("malformed JSON handling", () => {
it("throws for malformed numbers inside arrays", () => {
expect(() => parse("[1, .05, 2]")).toThrow(MalformedJSON);
});

it("throws for malformed numbers inside objects", () => {
expect(() => parse('{"a": .05, "b": 2}')).toThrow(MalformedJSON);
});

it("keeps parsing after an empty array with spaces", () => {
expect(parse('[{"id":1,"arr":["hello"]},{"id":2,"arr":[ ],"more":"yaya"},{"id":3,"arr":["!"]}]')).toEqual([
{ id: 1, arr: ["hello"] },
{ id: 2, arr: [], more: "yaya" },
{ id: 3, arr: ["!"] },
]);
});

it("keeps parsing after an object comma with spaces", () => {
expect(parse('{"a":1, }')).toEqual({ a: 1 });
});

it("keeps parsing after an array comma with spaces", () => {
expect(parse("[1, ]")).toEqual([1]);
});
});
20 changes: 16 additions & 4 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ const _parseJSON = (jsonString: string, allow: number) => {
throw new MalformedJSON(`${msg} at position ${index}`);
};

const isPartialJSON = (e: unknown) => e instanceof PartialJSON;

const parseAny: () => any = () => {
skipBlank();
if (index >= length) markPartialJSON("Unexpected end of input");
Expand Down Expand Up @@ -108,32 +110,42 @@ const _parseJSON = (jsonString: string, allow: number) => {
const value = parseAny();
obj[key] = value;
} catch (e) {
if (Allow.OBJ & allow) return obj;
else throw e;
if (Allow.OBJ & allow && isPartialJSON(e)) return obj;
throw e;
}
skipBlank();
if (jsonString[index] === ",") index++; // skip comma
if (jsonString[index] === ",") {
index++; // skip comma
skipBlank();
}
}
} catch (e) {
if (!isPartialJSON(e)) {
if (index >= length) markPartialJSON("Expected '}' at end of object");
throw e;
}
if (Allow.OBJ & allow) return obj;
else markPartialJSON("Expected '}' at end of object");
markPartialJSON("Expected '}' at end of object");
}
index++; // skip final brace
return obj;
};

const parseArr = () => {
index++; // skip initial bracket
skipBlank();
const arr = [];
try {
while (jsonString[index] !== "]") {
arr.push(parseAny());
skipBlank();
if (jsonString[index] === ",") {
index++; // skip comma
skipBlank();
}
}
} catch (e) {
if (!isPartialJSON(e)) throw e;
if (Allow.ARR & allow) {
return arr;
}
Expand Down