Implementing JSON.stringify() Using Recursion in JavaScript
Satish Shriwas¡Oct 29, 2026¡2 min read
Original on Medium âEver wondered how JSON.stringify() converts a nested JavaScript object into a string? Let's build a simplified version ourselves! đ
The idea
Every recursive call returns a JSON string representing the given value.
- Primitives: Return their string representation.
- Strings: Wrap them in double quotes.
- Arrays: Serialize each element and join with commas.
- Objects: Serialize each key-value pair and wrap them in braces.
Implementation
export default function jsonStringify(value) {
if (value === null) return 'null';
if (typeof value === 'string') {
return JSON.stringify(value);
}
if (typeof value === 'number' ||
typeof value === 'boolean') {
return String(value);
}
if (Array.isArray(value)) {
return '[' +
value.map(jsonStringify).join(',') +
']';
}
if (typeof value === 'object') {
return '{' +
Object.keys(value)
.map(key =>
jsonStringify(key) + ':' +
jsonStringify(value[key])
)
.join(',') +
'}';
}
}Letâs dry run it
jsonStringify({
name: 'Alex',
scores: [10, 20]
});Recursion serializes each value independently:
'Alex' â "\"Alex\""
[10, 20] â "[10,20]"
The object combines these results into:
{"name":"Alex","scores":[10,20]}The interview takeaway
The trick isnât JSON itselfâââitâs deciding what each recursive call should return.
Return a string at every level, and let arrays and objects combine those strings into the final result.
One caveat: this is a simplified implementation. It uses native JSON.stringify() to escape strings, so a fully independent implementation would need to handle string escaping and special numeric values separately.