Question

How to implement JSON.stringify?

Answer and Explanation

Implementing a custom JSON.stringify function is a complex task, as the standard JavaScript JSON.stringify handles various data types and edge cases. However, we can create a simplified version to understand the core concepts.

Here's how you can approach a basic implementation:

1. Handle Basic Types:

- Start by handling primitive data types like strings, numbers, booleans, and null.

2. Handle Arrays:

- Iterate through the array and recursively call the stringify function for each element. Enclose the result in square brackets [].

3. Handle Objects:

- Iterate through the object properties and recursively call the stringify function for each value. Enclose the result in curly braces {} with the key-value pairs separated by colons :.

4. Recursive Approach:

- The implementation will be recursive since an object or array may contain other nested objects and arrays.

5. Handle Special Values:

- Be mindful of special values like undefined, NaN and Infinity. The JSON.stringify function will normally return null for undefined and also handle numeric infinity values appropriately.

6. The Code:

function myStringify(obj) {
  if (obj === null) {
   return "null";
  }
  if (typeof obj === "boolean") {
   return obj ? "true" : "false";
  }
  if (typeof obj === "number") {
   return isFinite(obj) ? String(obj) : "null";
  }
  if (typeof obj === "string") {
   return `"` + obj.replace(/"/g, '\\"') + `"`;
  }
  if (typeof obj === "undefined" || typeof obj === "function"){
   return undefined;
  }
  if (Array.isArray(obj)) {
   let result = "[";
   for (let i = 0; i < obj.length; i++) {
   let element = myStringify(obj[i]);
   result += element === undefined ? "null" : element;
   if (i < obj.length - 1) result += ",";
   }
   result += "]";
   return result;
  }
  if (typeof obj === "object") {
   let result = "{";
   let keys = Object.keys(obj);
   for (let i = 0; i < keys.length; i++) {
    let key = keys[i];
    let value = myStringify(obj[key]);
    if(value !== undefined) {
     result += `"` + key + `":` + value;
     if (i < keys.length - 1) result += ",";
   }
   }
   result += "}";
   return result;
  }
  return undefined;
}

Example Usage:

const myObject = { name: "John", age: 30, isStudent: false, courses: ["Math", "English"] };
const jsonString = myStringify(myObject);
console.log(jsonString); // Output: {"name":"John","age":30,"isStudent":false,"courses":["Math","English"]}

This simplified implementation demonstrates the basic logic of how JSON.stringify works. Note that a complete implementation of JSON.stringify includes handling more complex cases, such as circular references, which are not addressed in this basic example.

More questions

Dashboard
Talk to AI
Image ID
AI Photos
Web Design