EN/CH Mode
BRUCE_FE JS Interview Notes - Implementing JSON.stringify
Learn how to hand-write JavaScript's JSON.stringify method implementation, deeply understand JSON serialization principles, and enhance frontend interview competitiveness.
EN/CH Mode
Lazy to read articles? Then watch videos!
JSON.stringify Method Overview
JSON.stringify
is the standard method for converting JavaScript values or objects to JSON strings. In frontend development, this method is commonly used for data transmission, storage, and serialization. Understanding its internal operation mechanism not only helps to use it better but also deepens understanding of JavaScript type systems and recursive algorithms.
Characteristics of JSON.stringify
- 1.
Handle Primitive Types
: Strings, numbers, booleans, null can be directly converted - 2.
Handle Complex Objects
: Objects and arrays recursively process their properties - 3.
Ignore Special Values
: undefined, functions, Symbol are ignored in objects - 4.
Handle Circular References
: Native method throws errors to avoid infinite recursion - 5.
Support Replacer
: Can use functions or arrays to customize serialization process - 6.
Support Formatting
: Can specify indentation to make output more readable
In interviews, hand-writing JSON.stringify
implementation is a good topic to test candidates' abilities in recursion, type handling, and edge case processing.
Implement a Simple Version of JSON.stringify
Solution: Implement a JSON.stringify that only supports basic functionality:
function basicJSONStringify(value) {
// Handle null
if (value === null) {
return 'null';
}
// Handle strings
if (typeof value === 'string') {
return '"' + value.replace(/"/g, '\\"') + '"';
}
// Handle numbers
if (typeof value === 'number') {
if (isNaN(value) || value === Infinity || value === -Infinity) {
return 'null';
}
return String(value);
}
// Handle booleans
if (typeof value === 'boolean') {
return String(value);
}
// Ignore undefined, functions and Symbol
if (typeof value === 'undefined' || typeof value === 'function' || typeof value === 'symbol') {
return undefined;
}
// Handle arrays
if (Array.isArray(value)) {
const items = value.map(item =>
basicJSONStringify(item) === undefined ? 'null' : basicJSONStringify(item)
);
return '[' + items.join(',') + ']';
}
// Handle objects
if (typeof value === 'object') {
const props = [];
for (const key in value) {
if (Object.prototype.hasOwnProperty.call(value, key)) {
const prop = basicJSONStringify(value[key]);
if (prop !== undefined) {
props.push('"' + key + '":' + prop);
}
}
}
return '{' + props.join(',') + '}';
}
return undefined;
}
// Test example
const obj = {
name: "Bruce",
age: 30,
isAdmin: false,
skills: ["JS", "React"],
address: { city: "Taipei" }
};
console.log(basicJSONStringify(obj));