The Final Code: Putting It All Together
Here's the complete function. It incorporates all the above steps to make a fully functional JSON parser in JavaScript.
JAVASCRIPT
1function parseJSON(input) {
2 // Edge Cases and Error Handling
3 if (input === "" || input[0] === "'") {
4 throw Error("Invalid JSON string");
5 }
6 if (input === "null") { return null; }
7 if (input === "{}") { return {}; }
8 if (input === "[]") { return []; }
9 if (input === "true") { return true; }
10 if (input === "false") { return false; }
11
12 // Parsing Strings
13 if (input[0] === '"') {
14 return input.slice(1, -1);
15 }
16
17 // Parsing Objects
18 if (input[0] === "{") {
19 return input
20 .slice(1, -1)
21 .split(",")
22 .reduce((acc, item) => {
23 const index = item.indexOf(":");
24 const key = item.slice(0, index);
25 const value = item.slice(index + 1);
26 acc[parseJSON(key)] = parseJSON(value);
27 return acc;
28 }, {});
29 }
30
31 // Parsing Arrays
32 if (input[0] === "[") {
33 return input
34 .slice(1, -1)
35 .split(",")
36 .map((x) => parseJSON(x));
37 }
38}
And there you have it—a JSON parser built from scratch.