AlgoDaily

Implement JSON.parse

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Question

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?

function parseJSON(input) {
    // fill in this method
}

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.

cover

Edge Cases

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.

if (input === "" || input[0] === "'") {
    throw Error("Invalid JSON string");
}
if (input === "null") {
    return null;
}
if (input === "{}") {
    return {};
}
if (input === "[]") {
    return [];
}
if (input === "true") {
    return true;
}
if (input === "false") {
    return false;
}

Parse Strings

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.

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

Parsing Objects

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.
if (input[0] === "{") {
    return input
        .slice(1, -1)
        .split(",")
        .reduce((acc, item) => {
            const index = item.indexOf(":");
            const key = item.slice(0, index);
            const value = item.slice(index + 1);
            acc[parse(key)] = parse(value);
            return acc;
        }, {});
}

Parsing Arrays

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.
if (input[0] === "[") {
    return input
        .slice(1, -1)
        .split(",")
        .map((x) => parse(x));
}

Final Code

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.

function parseJSON(input) {
    // Edge Cases and Error Handling
    if (input === "" || input[0] === "'") {
        throw Error("Invalid JSON string");
    }
    if (input === "null") { return null; }
    if (input === "{}") { return {}; }
    if (input === "[]") { return []; }
    if (input === "true") { return true; }
    if (input === "false") { return false; }

    // Parsing Strings
    if (input[0] === '"') {
        return input.slice(1, -1);
    }

    // Parsing Objects
    if (input[0] === "{") {
        return input
            .slice(1, -1)
            .split(",")
            .reduce((acc, item) => {
                const index = item.indexOf(":");
                const key = item.slice(0, index);
                const value = item.slice(index + 1);
                acc[parseJSON(key)] = parseJSON(value);
                return acc;
            }, {});
    }

    // Parsing Arrays
    if (input[0] === "[") {
        return input
            .slice(1, -1)
            .split(",")
            .map((x) => parseJSON(x));
    }
}

And there you have it—a JSON parser built from scratch.

One Pager Cheat Sheet

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.
Open interactive view →