Frontend101 logoFrontend101

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! 🚀

Photo by James Harrison on Unsplash

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.