JavaScript Object to JSON: Complete Conversion Guide
To convert a JavaScript object to JSON, use JSON.stringify(). The easy case is one line. The production case needs formatting, field filtering, and handling for values that JSON cannot represent.
Convert an object to a JSON string
Pass the object to JSON.stringify. The result is a string that can be sent over HTTP, saved to localStorage, written to a file, or pasted into another tool.
const user = {
id: 42,
name: 'Alice',
active: true,
roles: ['admin', 'editor']
}
const json = JSON.stringify(user)
console.log(typeof json)
// string
console.log(json)
// {"id":42,"name":"Alice","active":true,"roles":["admin","editor"]}Pretty print the JSON output
Add a third argument to create readable JSON. This is the most common form for debugging, config files, and examples in docs.
const pretty = JSON.stringify(user, null, 2)
// {
// "id": 42,
// "name": "Alice",
// "active": true,
// "roles": [
// "admin",
// "editor"
// ]
// }Convert only selected properties
Use a replacer array when you want an allowlist of keys. This is useful for small exports, examples, and log output.
const account = {
id: 42,
name: 'Alice',
email: 'alice@example.com',
passwordHash: 'do-not-export'
}
JSON.stringify(account, ['id', 'name'], 2)
// {
// "id": 42,
// "name": "Alice"
// }For security-sensitive fields, filter data before serialization too. A replacer is useful, but it should not be the only guard that protects secrets.
Transform values while converting
A replacer function can omit, normalize, or convert fields as JSON is created.
const json = JSON.stringify(account, (key, value) => {
if (key === 'passwordHash') return undefined
if (value instanceof Date) return value.toISOString()
if (typeof value === 'bigint') return value.toString()
return value
}, 2)This pattern is useful for API payloads, logs, and exports where you want a stable wire format.
Values that do not survive object to JSON conversion
undefined, functions, and symbols are omitted from objects.NaN,Infinity, and-Infinitybecomenull.Dateobjects become ISO strings.MapandSetdo not serialize as useful JSON by default.BigIntthrows unless converted first.- Circular references throw
TypeError.
Prepare objects before stringifying
If the object contains Maps, Sets, class instances, or database records, normalize it to plain JSON-compatible data first.
const settings = new Map([
['theme', 'dark'],
['density', 'compact']
])
const payload = {
settings: Object.fromEntries(settings),
exportedAt: new Date().toISOString()
}
JSON.stringify(payload, null, 2)Check the JSON before using it
Paste your generated JSON into Jsonic's JSON Formatter to validate syntax, inspect nesting, or minify the final payload.
Open JSON Formatter