JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JSON.parse()

15 April 2025 | Category:

The JSON.parse() method in JavaScript is used to convert a JSON string into a JavaScript object.

âś… In simple words:
JSON string → JavaScript object


📦 Syntax

JSON.parse(text[, reviver]);

Parameters:

  • text: A valid JSON string to be parsed.
  • reviver (optional): A function that allows transformation of the result before returning.

âś… Example 1: Basic Usage

const jsonStr = '{"name": "Alice", "age": 25}';

const user = JSON.parse(jsonStr);

console.log(user.name); // Output: Alice
console.log(user.age);  // Output: 25

âś… Example 2: Parsing Arrays

const jsonArray = '["HTML", "CSS", "JavaScript"]';

const skills = JSON.parse(jsonArray);

console.log(skills[1]); // Output: CSS

âť— Invalid JSON will cause an Error

const badJson = "{name: 'John'}"; // ❌ Invalid JSON

try {
  const obj = JSON.parse(badJson);
} catch (error) {
  console.error("Error parsing JSON:", error.message);
}

đź”§ Fix:

Always wrap keys and strings in double quotes:

const goodJson = '{"name": "John"}';

đź§  Optional: Using the Reviver Function

The reviver function allows you to modify values during parsing.

const jsonStr = '{"name": "John", "age": "30"}';

const person = JSON.parse(jsonStr, (key, value) => {
  if (key === "age") {
    return Number(value); // Convert age to number
  }
  return value;
});

console.log(person.age); // Output: 30 (number)

âś… Summary

FeatureDescription
PurposeConverts JSON string → JavaScript object
InputMust be a valid JSON string
Common Use CaseReading data from APIs or localStorage
Optional reviverCustom processing while parsing