Exchange a data format, not executable code
JSON represents objects, arrays, strings, numbers, booleans and null in a text format. JSON.parse converts valid JSON text into JavaScript values. JSON.stringify serializes supported values. JSON is not the same syntax as an arbitrary JavaScript object literal.
const student = { name: 'Asha', score: 82, passed: true };
const text = JSON.stringify(student);
console.log(text); // {"name":"Asha","score":82,"passed":true}
const restored = JSON.parse(text);
console.log(restored.score); // 82JSON property names and strings use double quotes. Comments, trailing commas and undefined are not valid JSON values. Never replace JSON.parse with eval to accept an untrusted response.
Validate after parsing
function readProgress(text) {
const value = JSON.parse(text);
if (value === null || typeof value !== 'object' || Array.isArray(value)
|| !Number.isInteger(value.completed) || value.completed < 0) {
throw new TypeError('Invalid progress record');
}
return { completed: value.completed };
}
console.log(readProgress('{"completed":3}')); // { completed: 3 }Valid JSON can still have the wrong shape. A successful parse does not establish that a payload is a permitted user, safe HTML or a trustworthy authorization claim.
Serialization limitations
Object properties whose values are undefined or functions are omitted; such array entries serialize differently, commonly as null. Date normally serializes to a string. Circular references throw, and BigInt needs an explicit representation strategy. Map, Set and class prototypes do not round-trip as their original types automatically.
Numbers and copies
Large JSON numbers can lose precision when parsed into Number. Use a documented string representation for identifiers that must remain exact. stringify/parse is therefore not a universal deep-clone technique; choose a method matching the actual data types.
Practice
- Parse malformed JSON inside try/catch and show a useful recovery state.
- Test readProgress with null, an array and a negative count.
- Serialize a Date and inspect the restored type.
- Compare a missing object property with an explicit null property in serialized output.