Mark As Completed Discussion

Good morning! Here's our prompt for today.

In JavaScript by default, there is a method that can parse a given JSON string, and it can be invoked by calling JSON.parse(). The way this method works is constructing the JavaScript value or object described by the string.

Can you implement your own version of this method, called parseJSON, accepting one parameter (the JSON string), keeping in mind all the value types and restrictions in the JSON format?

JAVASCRIPT
1function parseJSON(input) {
2	// fill in this method
3}

Your task is to create a function called parseJSON that takes a string as input and returns the corresponding JavaScript object. The function should be able to handle JSON-like strings, which can be:

  • Primitive types: null, true, false
  • Strings wrapped in quotes: "string"
  • Arrays: [1, "a", null]
  • Objects: {"key": "value", "anotherKey": 42}

Your parser should return the corresponding JavaScript types for these string inputs. For example, if the input string is "null", your function should return null.

Question

Try to solve this here or in Interactive Mode.

How do I practice this challenge?

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Here's a video of us explaining the solution.

To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

Here's how we would solve this problem...

How do I use this guide?

How to Build a Simple JSON Parser in JavaScript

JSON, or JavaScript Object Notation, is a lightweight data-interchange format that is easy to read and write. We often encounter it while working with APIs and server-side data. Let's delve into the intricacies of parsing JSON, step by step.

Addressing Edge Cases: Simple Types and Errors

Why Handle Edge Cases?

Before we even think about parsing complex objects or arrays, let's handle some edge cases. These are simple data types or even errors that might make our parser trip if we don't deal with them first.

How to Handle?

We'll use if statements to check if our input string is one of these edge cases and return the corresponding JavaScript object.

JAVASCRIPT
1if (input === "" || input[0] === "'") {
2    throw Error("Invalid JSON string");
3}
4if (input === "null") {
5    return null;
6}
7if (input === "{}") {
8    return {};
9}
10if (input === "[]") {
11    return [];
12}
13if (input === "true") {
14    return true;
15}
16if (input === "false") {
17    return false;
18}

Parsing JSON Strings

The Importance of Quotation Marks

When parsing JSON data, a key or a string value is always wrapped between double quotation marks. This is our cue to focus on them.

The Parsing Technique

We use slice(1, -1) to get the content between the quotation marks, and we check if the first character is a quotation mark (") to know when to do this.

JAVASCRIPT
1if (input[0] === '"') {
2    return input.slice(1, -1);
3}

Parsing JSON Objects

The Curly Braces

In JSON, objects are wrapped in curly braces {}. This will be our signal to dive deeper and parse the properties inside it.

The Approach

  1. Slice the Braces: Remove the starting and ending curly braces.
  2. Split Properties: Split the string by commas to get individual "key": "value" strings.
  3. Key-Value Parsing: Use indexOf(":") to find where the key ends and the value starts, then slice the string to get both parts.
  4. Recursive Parsing: We call the parse function recursively to handle nested objects.
JAVASCRIPT
1if (input[0] === "{") {
2    return input
3        .slice(1, -1)
4        .split(",")
5        .reduce((acc, item) => {
6            const index = item.indexOf(":");
7            const key = item.slice(0, index);
8            const value = item.slice(index + 1);
9            acc[parse(key)] = parse(value);
10            return acc;
11        }, {});
12}

Parsing JSON Arrays

Square Brackets

In JSON, arrays are enclosed in square brackets []. This is our signal to parse them as arrays.

Steps to Parse

  1. Slice the Brackets: We remove the opening and closing square brackets.
  2. Split Elements: Then, we split the string by commas to get individual array elements.
  3. Recursive Parsing: We call the parse function recursively for each element to handle nested arrays.
JAVASCRIPT
1if (input[0] === "[") {
2    return input
3        .slice(1, -1)
4        .split(",")
5        .map((x) => parse(x));
6}

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.

One Pager Cheat Sheet

  • You can implement your own version of the JSON.parse() method, called parseJSON, that accepts one parameter and can return one of the following: array, object, string, number, boolean, or null.
  • By defining multiple if cases to check for null, empty objects, arrays or booleans and additional parsing of values inside quotes and brackets, we can create a JSON Parser in JavaScript.

This is our final solution.

To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

That's all we've got! Let's move on to the next tutorial.

If you had any problems with this tutorial, check out the main forum thread here.