What is JSON?
JSON (JavaScript Object Notation) is a lightweight data format for exchanging data.
It supports strings, numbers, booleans, null, arrays, and objects.
JSON is language-agnostic and widely used in APIs and configuration files.
JavaScript Tutorial
JSON is the standard format for data exchange on the web.
Learn how to parse, stringify, and validate JSON safely.
Most APIs send JSON, so you must parse and validate data correctly.
Understanding JSON prevents runtime errors and data loss.
JSON.parse(jsonString);
JSON.stringify(value);const json = '{"name":"Asha","age":21}';
const user = JSON.parse(json);
console.log(user.name);JSON.parse converts a JSON string into an object.
function safeParse(str) {
try {
return JSON.parse(str);
} catch {
return null;
}
}
console.log(safeParse('{"ok":true}'));
console.log(safeParse('invalid'));Use try/catch to avoid crashes on invalid JSON.
JSON (JavaScript Object Notation) is a lightweight data format for exchanging data.
It supports strings, numbers, booleans, null, arrays, and objects.
JSON is language-agnostic and widely used in APIs and configuration files.
Use JSON.parse() to convert a JSON string into a JavaScript value.
Wrap parsing in try/catch to handle invalid JSON.
Validate shape after parsing to avoid runtime errors.
Use JSON.stringify() to convert JavaScript values into JSON strings.
Functions, undefined, and symbols are not serialized.
Use replacer and spacing options for custom output.
Dates become strings when stringified and lose timezone behavior.
Circular references throw errors during JSON.stringify().
Precision can be lost with large numbers; consider BigInt or strings.
const user = { name: "Asha", age: 21 };
const json = JSON.stringify(user);
console.log(json);JSON.stringify converts objects into JSON strings.
const user = { name: "Asha", password: "secret" };
const json = JSON.stringify(user, (key, value) => (key === "password" ? undefined : value), 2);
console.log(json);Use a replacer to remove fields and spacing for readability.
Without
// Risky parse
const data = JSON.parse(input);With
// Safe parse
const data = (() => {
try { return JSON.parse(input); } catch { return null; }
})();Functions are skipped by JSON.stringify.
Wrap JSON.parse in try/catch and handle failures.
Remove cycles or use a custom serializer.
It converts a JSON string into a JavaScript value.
Functions, undefined, and symbols.
Use try/catch and return a fallback.
Practice: Parse a JSON string and log a field.
const json = '{"name":"Riya","age":20}';
// TODO: parse and log name
One Possible Solution
const json = '{"name":"Riya","age":20}';
const user = JSON.parse(json);
console.log(user.name);No. JSON is a string format with stricter rules.
Because the input string is not valid JSON.
Dates are stored as strings and must be rehydrated.
Use JSON.stringify(value, null, 2).
Try parsing a JSON string and reading a property.