JavaScript Object to JSON: Complete Conversion Guide
Last updated:
JSON.stringify(value, replacer, space) converts any JavaScript object to a JSON string. Pass an array of key names as the replacer to whitelist fields; pass 2 as the space argument for 2-space pretty-printing. Three value types are silently dropped from object properties: undefined, functions, and Symbol-keyed properties; the same types become null inside arrays. NaN and Infinity also serialize to null; BigInt and circular references both throw a TypeError. This guide covers the 3-argument signature, handling undefined and functions, fixing circular references with a custom replacer, Date serialization, and the toJSON() method for controlling class instance output.
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"]}To turn that string back into runtime data, use JSON to JavaScript object.
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"
// ]
// }There is also a dedicated guide for pretty printing JSON in JavaScript.
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 FormatterFrequently asked questions
What is the difference between JSON.stringify and JSON.parse?
JSON.stringify converts a JavaScript value into a JSON string (serialization). JSON.parse converts a JSON string back into a JavaScript value (deserialization). Use stringify when sending data, parse when receiving it.
Which JavaScript values cannot be serialized to JSON?
Functions, undefined, and symbols are omitted from objects or becomenull in arrays. NaN and Infinity becomenull. BigInt throws. Map and Setdo not serialize usefully by default.
How do I convert an object to a JSON string?
Call JSON.stringify(object) for a compact string, orJSON.stringify(object, null, 2) for readable indented output. Pass an array of key names as the second argument to include only specific fields.
What happens to functions in JSON.stringify?
Functions are silently dropped from object properties. Inside arrays, they becomenull. JSON is a data format and cannot represent executable code.
How do I convert a class instance to JSON?
JSON.stringify serializes enumerable own properties. Add a toJSON() method to the class to control exactly which fields are included and how they are formatted.
What is the toJSON method?
If an object defines toJSON(), JSON.stringify calls it and serializes the return value instead of the object itself. Use it to strip private fields, convert non-serializable types, and produce a stable wire format.
Recommended reading
- Effective TypeScript (2nd Edition) — Dan Vanderkam83 concrete ways to level up your TypeScript — inference, narrowing, and type-safe API boundaries.
- JavaScript: The Definitive Guide (7th Edition) — David FlanaganThe complete reference for the language JSON came from — serialization, async, and the full standard library.
As an Amazon Associate, Jsonic earns from qualifying purchases.