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
- Dispatch on type:
nullbecomes the textnull; a string is wrapped in double quotes; numbers and booleans useString(v). - Arrays serialise as an opening bracket, the recursively serialised elements joined by commas, and a closing bracket.
- Objects serialise as an opening brace, each
key:valuepair with the key quoted, joined by commas, and a closing brace. - JSON omits
undefinedand functions: inside an object such a key is skipped, and inside an array the value becomesnull. 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
nullspecial case:typeof nullisobject, 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 []isobject, soArray.isArrayis 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.