Json Parse in JavaScript
JSON.parse() in JavaScript
What is JSON.parse()?
JSON.parse()is a built-in JavaScript method.It converts a JSON-formatted string into a JavaScript object or value.
Used to parse JSON data received as a string (e.g., from a server) into usable JavaScript objects.
Syntax
JSON.parse(text[, reviver])text: A valid JSON string to parse.
reviver (optional): A function that can transform the parsed result before returning it.
Basic Example
const jsonString = '{"name":"John", "age":30, "isStudent":false}';const obj = JSON.parse(jsonString);console.log(obj.name); // Output: Johnconsole.log(obj.age); // Output: 30console.log(obj.isStudent); // Output: falseUsing the reviver Parameter
The reviver is a function called for each key-value pair in the parsed object. It allows you to modify the values during parsing.
const jsonString = '{"name":"John","birthdate":"1990-01-01"}';const obj = JSON.parse(jsonString, (key, value) => { if (key === "birthdate") { return new Date(value); // Convert birthdate string to Date object } return value;});console.log(obj.birthdate instanceof Date); // trueconsole.log(obj.birthdate.toDateString()); // e.g. "Mon Jan 01 1990"Important Notes
Input must be a valid JSON string; otherwise,
JSON.parse()throws aSyntaxError.Strings must use double quotes (
" "), not single quotes.Cannot parse functions or undefined values.
Example of Error
try { JSON.parse("{name: 'John'}"); // Invalid JSON (keys must be in quotes)} catch (error) { console.error("Parsing failed:", error.message);}If you want, I can help you with examples to safely parse JSON or handle errors during parsing!