⚡Flashcard Drill➔
NeetCode #961LC-2633MediumJavaScript
← Back to All Problems

#961 · #2633 · Convert Object to JSON String(将对象转换为 JSON 字符串)

📌 Problem Statement & Constraints

Implement jsonStringify(object), converting any serialisable value (object, array, string, number, boolean, null) into a JSON string. The built-in JSON.stringify must not be used.

💡 Core Algorithmic Approaches

  1. Dispatch on type: null becomes the text null; a string is wrapped in double quotes; numbers and booleans use String(v).
  2. Arrays serialise as an opening bracket, the recursively serialised elements joined by commas, and a closing bracket.
  3. Objects serialise as an opening brace, each key:value pair with the key quoted, joined by commas, and a closing brace.
  4. JSON omits undefined and functions: inside an object such a key is skipped, and inside an array the value becomes null. The test cases do not exercise this, but it is worth knowing.

💻 Benchmark Python3 Implementation

var jsonStringify = function(object) {
    if (object === null) return "null";
    if (typeof object === "string") return '"' + object + '"';
    if (typeof object === "number" || typeof object === "boolean") {
        return String(object);
    }
    if (Array.isArray(object)) {
        return "[" + object.map(jsonStringify).join(",") + "]";
    }
    if (typeof object === "object") {
        const parts = Object.keys(object)
            .map(k => '"' + k + '":' + jsonStringify(object[k]));
        return "{" + parts.join(",") + "}";
    }
    return undefined;                          // undefined / function
};

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(N): N is the total number of nodes.
💾 Space Complexity
O(D): the recursion depth.

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting the null special case: typeof null is object, so it would enter the object branch and crash.
  • Not quoting string values: JSON strings must be wrapped in double quotes, never single quotes.
  • Serialising object keys without quotes: JSON requires every key to be a double-quoted string.
  • Detecting arrays by typeof: typeof [] is object, so Array.isArray is essential to avoid the object branch.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related JavaScript Problems