How to convert an object to JSON
Short answer
JSON.stringify() turns an object into a JSON string:
const user = { name: 'Anna', age: 30, admin: false };
console.log(JSON.stringify(user));Output:
{"name":"Anna","age":30,"admin":false}Readable format
The third argument sets the indent. That is handy for logs and files:
const user = { name: 'Anna', roles: ['admin'] };
console.log(JSON.stringify(user, null, 2));Output:
{
"name": "Anna",
"roles": [
"admin"
]
}Only some fields
The second argument can be an array of keys to keep:
const user = { name: 'Anna', password: 'secret', email: 'anna@example.com' };
console.log(JSON.stringify(user, ['name', 'email']));Output:
{"name":"Anna","email":"anna@example.com"}Common mistake
Some values do not survive conversion: functions and undefined disappear, NaN turns into null, and dates become strings:
const data = { a: undefined, b: () => 1, c: NaN, d: new Date(Date.UTC(2025, 0, 1)) };
console.log(JSON.stringify(data));Output:
{"c":null,"d":"2025-01-01T00:00:00.000Z"}Functions used in this recipe
- JSON.stringify — Converts a value to a JSON string.
- JSON.parse — Parses a JSON string and returns the value.