Two situations, two answers
The object exists in running code. Use JSON.stringify. It is built into every browser and Node.js, and it produces valid JSON:
const user = { id: 42, name: "Ada", roles: ["admin"] };
const json = JSON.stringify(user); // '{"id":42,"name":"Ada","roles":["admin"]}'
const pretty = JSON.stringify(user, null, 2);
You only have the source text, copied from a file, a code review, the console or documentation. Then you need to convert the syntax. Paste it into the tool above. It reads the literal without evaluating it, so a function inside it is never run, and writes the JSON that JSON.stringify would have produced. The example above becomes:
{
"id": 42,
"name": "Ada",
"created": "2024-05-01T09:30:00.000Z",
"roles": ["admin", "editor"],
"settings": {},
"ratio": null,
"accountId": 12345678901234567890
}
email, greet and onSave are gone, the Map is {}, and NaN is null. That matches JSON.stringify. The one difference is deliberate: JSON.stringify throws on the BigInt, while the converter writes its digits exactly.
Object literal syntax that is not JSON
| In a JS literal | In JSON | Converter |
|---|---|---|
{name: 1} | {"name": 1} | Keys quoted (more) |
'text', `text` | "text" | Converted, escapes decoded (more) |
[1, 2,], {a: 1,} | [1, 2], {"a": 1} | Trailing commas removed (more) |
// note, /* note */ | not allowed | Removed (more) |
0xFF, 1_000, .5 | 255, 1000, 0.5 | Normalised |
const x = {...}; | just the {...} | Assignment and semicolon removed |
`Hi ${name}` | no equivalent | Kept as plain text, with a warning |
...spread, variables | no equivalent | Reported as an error. These need the running code. |
What JSON.stringify does with each value type
| Value | As an object property | In an array | At the top level |
|---|---|---|---|
undefined | property omitted | null | returns undefined (not a string) |
| function, method, arrow function | property omitted | null | returns undefined |
Symbol() | property omitted | null | returns undefined |
NaN, Infinity | null | null | "null" |
new Date(...) | ISO 8601 string via Date.prototype.toJSON, e.g. "2024-05-01T09:30:00.000Z", always in UTC. An invalid date becomes null. | ||
Map, Set, WeakMap | {}: their entries are not enumerable properties | ||
123n (BigInt) | throws TypeError: Do not know how to serialize a BigInt (Chrome / Node.js wording) | ||
| circular reference | throws TypeError: Converting circular structure to JSON (Chrome / Node.js) | ||
| class instance | its own enumerable properties, as a plain object. The class and its methods are lost. | ||
object with toJSON() | whatever toJSON() returns | ||
Properties with Symbol keys and non-enumerable properties are skipped too. None of this produces an error, so data can go missing without anyone noticing. If a field is absent after a round trip, check this table first.
The replacer and space arguments
JSON.stringify(value, replacer, space) has two optional arguments that solve most "how do I make it output X" questions.
space: indentation
JSON.stringify(obj, null, 2); // 2 spaces
JSON.stringify(obj, null, "\t"); // tabs
// numbers above 10 are clamped to 10; strings longer than 10 characters are cut to 10
replacer as an array: keep only some keys
JSON.stringify(user, ["id", "name"]); // '{"id":42,"name":"Ada"}'
replacer as a function: transform values
const json = JSON.stringify(data, (key, value) => {
if (typeof value === "bigint") return value.toString(); // avoid the BigInt TypeError
if (value instanceof Map) return Object.fromEntries(value); // keep Map entries
if (value instanceof Set) return [...value]; // keep Set items
if (key === "password") return undefined; // drop a field
return value;
});
The function is called with this set to the containing object, and it runs after toJSON. So for a Date, value is already the ISO string. Check this[key] instanceof Date if you need the original Date object.
Circular structures
Objects that point back to themselves, such as DOM nodes, framework component instances or parent links in a tree, cannot be written as JSON. Either delete the back-references before serialising, or use a replacer that remembers what it has already seen:
function safeStringify(obj, space) {
const seen = new WeakSet();
return JSON.stringify(obj, (k, v) => {
if (typeof v === "object" && v !== null) {
if (seen.has(v)) return "[Circular]";
seen.add(v);
}
return v;
}, space);
}
This also replaces objects that merely appear twice, which are not actually circular. It is fine for logging but not for data you need to read back.
JSON5: when you want the loose syntax
If people write the files by hand and you want comments, unquoted keys and trailing commas, use JSON5 as the file format and convert at the boundary: JSON.stringify(JSON5.parse(text)). Keep plain JSON for anything that goes over the network or to other languages.
Watch out for big numbers
A JavaScript number holds integers exactly only up to 9007199254740991 (Number.MAX_SAFE_INTEGER). An ID like 12345678901234567890 written in source code is already rounded before JSON.stringify runs. This converter works on the text, so it keeps every digit, but any JavaScript code that reads the JSON with JSON.parse will round it again. Send such values as strings. See JSON big integer precision.
FAQ
How do I convert a JavaScript object to JSON?
Call JSON.stringify(obj). It returns a JSON string. Use JSON.stringify(obj, null, 2) for indented output. If you only have the object as source text, paste it into the converter above, which converts it without running it.
How do I convert a JavaScript object to a JSON string and back?
JSON.stringify(obj) gives you the string, and JSON.parse(text) turns the string back into an object. A round trip loses anything JSON cannot represent: functions and undefined disappear, Dates come back as strings, and Map and Set come back as empty objects.
Why does JSON.stringify drop some properties?
Properties whose value is undefined, a function or a Symbol are left out of objects. In arrays they become null so the positions stay the same. Properties with Symbol keys and non-enumerable properties are also skipped.
Why does JSON.stringify throw "Do not know how to serialize a BigInt"?
JSON.stringify has no built-in rule for BigInt values and throws a TypeError. Convert them first, for example with a replacer: JSON.stringify(obj, (k, v) => typeof v === "bigint" ? v.toString() : v). Sending big IDs as strings is the safest choice for any JavaScript client.
Why is my Map or Set empty in the JSON?
Map and Set keep their entries internally, not as enumerable properties, so JSON.stringify writes {}. Convert them first: Object.fromEntries(map) for a Map with string keys, or [...set] for a Set.
What do the second and third arguments of JSON.stringify do?
The second argument is a replacer: a function called for every key and value, or an array of key names to keep. The third is the indentation: a number of spaces up to 10, or a string such as "\t".
Is a JavaScript object the same as JSON?
No. A JavaScript object is a value in memory, and an object literal is code that creates one. JSON is a text format with stricter syntax: double-quoted keys and strings, no trailing commas, no comments, no functions and no undefined.