JavaScript Object to JSON

Summary
Definition: JavaScript objects can be serialized to JSON text and parsed back into values.
Why it matters: Correct JSON handling prevents data loss and runtime errors.
Pitfall: JSON only supports a limited set of data types.
JSON.stringify converts JavaScript values into JSON text. JSON.parse turns JSON text back into values.
This process is lossy for many JavaScript types.
- JSON
- Text-based data format defined by standards.
- Serialization
- Converting values into JSON text.
- Parsing
- Converting JSON text into values.
- Lossy
- Information is discarded during conversion.
- Circular ref
- Object that references itself.
What JSON.stringify does
JSON.stringify converts supported JavaScript values into a JSON string. Unsupported values are skipped or cause errors.
Common mix-up: JSON.stringify does not clone objects; it produces lossy text output.
In arrays, skipped values like undefined become null instead of being removed.
Quick example
Plain objects round-trip with JSON.stringify and JSON.parse.
const payload = { id: 42, name: "Ada" };
const json = JSON.stringify(payload);
const parsed = JSON.parse(json);Dates and custom handling
Date objects serialize using toJSON and become ISO strings.
Dates become strings during serialization.
const data = { created: new Date() };
JSON.stringify(data);
// {"created":"2026-01-18T12:00:00.000Z"}Handling parse errors
JSON.parse throws if the input is invalid JSON.
Wrap JSON.parse in try/catch.
function safeParse(text) {
try {
return JSON.parse(text);
} catch {
return null;
}
}Never trust JSON input from external sources without validation.
Practical check
- Serialize a plain object.
- Parse it back using try/catch.
- Add a Date and confirm it becomes a string.
- Test invalid JSON input.