JavaScript › JSON & Data Serialization

How do you convert a JavaScript object into a JSON string?

Beginner

Answer

JSON.stringify() serializes a JavaScript value into a JSON-formatted string, converting objects, arrays, strings, numbers, booleans, and null into their JSON text representation.
const obj = { name: 'Sam', age: 30 };
const json = JSON.stringify(obj);
console.log(json); // '{"name":"Sam","age":30}'
Real-world example Preparing a JavaScript object to send as the body of a fetch() POST request.

Common follow-ups: What happens to functions or undefined values when you stringify an object containing them?