AlgoDaily

Implement JSON.stringify

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 there is a method called JSON.stringify() that can convert an object or a variable into a JSON string. The method handles different data types differently, ending up with its correct JSON "translation". Some examples of how this method handles different types include:

  • Boolean, Number, and String objects are converted to the corresponding primitive values
  • undefined, Function, and Symbol are not valid JSON values and are changed to null
  • The instances of Date are returned as date.toISOString() and are treated as strings
  • Infinity as well as the value null are considered as null

Can you implement a simplified version of this JSON stringifier, covering the most important constraints when it comes to the data type and value handling?

Here is an example of how your solution should work:

stringify({});                    // '{}'
stringify(true);                  // 'true'
stringify('foo');                 // '"foo"'
stringify([1, 'false', false]);   // '[1,"false",false]'
stringify([null, Infinity]);      // '[null,null]'
stringify({ x: 5 });              // '{"x":5}'

cover

Solution

Solution

Our solution would be the method stringify, that will simply handle the cases we mentioned above, with many different if conditions. For example, we return undefined if the type of the data is a function, or we return null if it is a synbol, undefined, infinity, or null.

if (typeof data === "function") {
    return undefined;
}
if (data === Infinity || data === -Infinity || data === null
    || data === undefined || typeof data === "symbol") {
    return "null";
}

If the data is a string, number or a boolean, we return the data itself, bearing in mind the quotes needed for a string value.

if (typeof data === "string") {
    return `"${data}"`;
}
if (typeof data === "number" || typeof data === "boolean") {
    return `${data}`;
}

If our data type is a date, as stated above, we return it as a string, by using data.toISOString().

In case we are dealing with an array, or an object, then we need a bit more logic to parse our data. So, for an array, we will first map and stringify our data to make sure the elements are all in a string format, and then we are going to parse it in the needed JSON array format, using braces, and separate the data with commas:

if (Array.isArray(data)) {
    const arr = data.map((el) => stringify(el));
    return `[${arr.join(",")}]`;
}

For objects, we will handle them by looping the object properties one by one, and then using the reduce method we will divide them into key-value pairs - key being the property name, and the value being its value. We will perserve the JSON objects notation, wrapping the object properties into brackets, and in the format "key": "value".

if (typeof data === "object") {
    const arr = Object.entries(data).reduce((acc, [key, value]) => {
        if (value === undefined) {
            return acc;
        }
        acc.push(`"${key}":${stringify(value)}`);
        return acc;
    }, []);
    return `{${arr.join(",")}}`;
}

Our final solution with all these conditions handled would look like this:

function stringify(data) {
    if (typeof data === "string") {
        return `"${data}"`;
    }
    if (typeof data === "function") {
        return undefined;
    }
    if (data === Infinity || data === -Infinity || data === null
        || data === undefined || typeof data === "symbol") {
        return "null";
    }
    if (typeof data === "number" || typeof data === "boolean") {
        return `${data}`;
    }

    if (data instanceof Date) {
        return `"${data.toISOString()}"`;
    }
    if (Array.isArray(data)) {
        const arr = data.map((el) => stringify(el));
        return `[${arr.join(",")}]`;
    }
    if (typeof data === "object") {
        const arr = Object.entries(data).reduce((acc, [key, value]) => {
            if (value === undefined) {
                return acc;
            }
            acc.push(`"${key}":${stringify(value)}`);
            return acc;
        }, []);
        return `{${arr.join(",")}}`;
    }
}

One Pager Cheat Sheet

One Pager Cheat Sheet

  • You can create a simplified version of the JSON.stringify() method to correctly handle different data types and values in order to successfully "translate" them into JSON strings.
  • We bold implemented a stringify method that handles different data types, such as functions, strings, numbers, booleans, dates, arrays, and objects, returning the corresponding strings or null as needed.
Open interactive view →