Module 6: Modern JavaScript, OOP, and Data
JSON and Working with Data
Serialize data with JSON and validate external data before using it.
JSON is a text format commonly used for APIs, configuration, and data exchange. JavaScript provides JSON.stringify to serialize supported values and JSON.parse to parse JSON text.
const course = { title: "JavaScript", lessons: 52 };
const json = JSON.stringify(course);
const restored = JSON.parse(json);
console.log(restored.title);
JSON supports objects, arrays, strings, numbers, booleans, and null. It does not preserve functions, undefined, symbols, prototypes, or many specialised object types. A Date is usually serialized as a string, so parse or construct it deliberately when restoring data.
Handle malformed data#
function parseJsonSafely(text) {
try {
return { ok: true, value: JSON.parse(text) };
} catch {
return { ok: false, value: null };
}
}
Valid JSON is not necessarily valid for your application's purpose. Validate required properties, allowed value ranges, and expected types before trusting the parsed result.
Security note#
Treat data from network responses, local storage, and user input as untrusted. Avoid turning untrusted strings into executable code. Do not use eval to parse JSON; use JSON.parse.
Practice#
Serialize an object containing a title and an array of lessons. Parse it back, then test how parsing behaves when the input string is malformed.