Building a Custom JSON Stringify Function in JavaScript

Building a Custom JSON Stringify Function in JavaScript

A comprehensive guide to understanding and implementing a custom JSON stringification process in javaScript

·

4 min read

JSON (JavaScript Object Notation) is a widely used data interchange format that allows easy data exchange between different programming languages. In JavaScript, the JSON.stringify() method is commonly used to convert JavaScript objects into JSON strings. However, understanding how to manually implement a JSON stringify function can deepen your understanding of JavaScript and serialization processes. In this blog post, we'll explore the inner workings of a custom JSON stringify function, step by step.

Understanding JSON and serialization:

Before diving into the implementation, let's briefly review JSON and the serialization process. JSON is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. Serialization is the process of converting an object into a format that can be easily transmitted or stored.

Basics Requirements:

Our custom JSON stringify function should handle various data types, including objects, arrays, strings, and primitive types. To achieve this, we'll need to recursively traverse the input data and build the corresponding JSON string.

let's break it down and understand it by implementing the customStringify function which will behave similarly to JSON.stringify().

Part 1: The basic structure of implementation:

function customStringify(value) {
    if (typeof value === 'object' && value !== null) {
        // Handle objects and arrays
        // ...
    } else if (typeof value === 'string') {
        // Handle strings
        // ...
    } else {
        // Handle other primitive types
        // ...
    }
}
  • The function customStringify takes a value parameter, representing the JavaScript value to be converted into a JSON string.

  • It begins with a check to determine if the value is an object (excluding null).

  • Depending on the type of the value, it will follow different branches to handle objects, arrays, strings, and other primitive types.

Part 2: Handling Objects and Arrays

Let's write the logic for handling the array first:

function customStringify(value) {
    if (typeof value === 'object' && value !== null) {
        // handle array
        if (Array.isArray(value)) {
            let result = '[';
            for (let i = 0; i < value.length; i++) {
                if (i > 0) {
                    result += ',';
                }
                result += customStringify(value[i]);
            }
            result += ']';
            return result;    
        }

        // TODO: handle object

    } else if (typeof value === 'string') {
        // TODO: handle string input

    } else {
        // TODO: handle other input type
    }
}
  • This part of the code checks if the value is an array using Array.isArray(value).

  • If it is an array, it iterates through each element, recursively calling customStringify on each element, and building the resulting string.

Now, we have handled array input, but in javascript, both array and object are of type 'object' only, so if this condition if (typeof value === 'object' && value !== null) passed, it means the value can be an array or an object, but we already handled the case of an array, so now let's handle the case of an object.

function customStringify(value) {
    if (typeof value === 'object' && value !== null) {
        // handle array
        if (Array.isArray(value)) {
            // implementation to handle array
        }else {
            // handle object
            let result = '{';
            let first = true;
            for (let key in value) {
                if (value.hasOwnProperty(key)) {
                    if (!first) {
                        result += ',';
                    }
                    result += '"' + key + '":' + customStringify(value[key]);
                    first = false;
                }
            }
            result += '}';
            return result;
        }
    } else if (typeof value === 'string') {
        // TODO: handle string input

    } else {
        // TODO: handle other input type
    }
}
  • If the value is an object, it iterates through its properties, recursively calling customStringify on each property value, and building the resulting string with key-value pairs.

Part 3: Handling string and other primitive types.

function customStringify(value) {
    if (typeof value === 'object' && value !== null) {
        // handle array and object type
    } else if (typeof value === 'string') {
        // Handle strings
        return '"' + value + '"';
    } else {
        // Handle other primitive types
        return String(value);
    }
}
  • If the value is a string, it encloses the string within double quotes and returns the result.

  • If the value is any other primitive type, it converts it to a string using String(value) and returns the result.

Final code:

function customStringify(value) {
    if (typeof value === 'object' && value !== null) {
        if (Array.isArray(value)) {
            // Handle arrays
            let result = '[';
            for (let i = 0; i < value.length; i++) {
                if (i > 0) {
                    result += ',';
                }
                result += customStringify(value[i]);
            }
            result += ']';
            return result;
        } else {
            // Handle objects
            let result = '{';
            let first = true;
            for (let key in value) {
                if (value.hasOwnProperty(key)) {
                    if (!first) {
                        result += ',';
                    }
                    result += '"' + key + '":' + customStringify(value[key]);
                    first = false;
                }
            }
            result += '}';
            return result;
        }
    } else if (typeof value === 'string') {
        // Handle strings
        return '"' + value + '"';
    } else {
        // Handle other primitive types
        return String(value);
    }
}

// Example usage
const obj = { name: 'Harry', age: 30, city: 'India' };
const jsonString = customStringify(obj);
console.log(jsonString);

Did you find this article valuable?

Support Md Talha by becoming a sponsor. Any amount is appreciated!