JSON.parse()

The JSON.parse() method in JavaScript is used to parse a JSON string and convert it into a JavaScript object. This is commonly used when working with data fetched from a server or when reading JSON-formatted data from a file or API.

Syntax

JSON.parse(text[, reviver]);

Parameters:

  1. text:
    • The JSON string to be parsed.
    • Must follow valid JSON syntax, otherwise, it throws a SyntaxError.
  2. reviver (Optional):
    • A function that transforms the resulting object before it’s returned.
    • It can be used to modify or filter values during the parsing process.

Examples

Basic Usage

Convert a JSON string into a JavaScript object:

const jsonString = '{"name": "Alice", "age": 25}';
const user = JSON.parse(jsonString);
console.log(user.name); // Output: Alice

Using the reviver Parameter

The reviver function processes each key-value pair in the parsed object. For example:

const jsonString = '{"price": "100", "quantity": "2"}';
const data = JSON.parse(jsonString, (key, value) => {
    if (key === "price" || key === "quantity") {
        return Number(value); // Convert strings to numbers
    }
    return value;
});
console.log(data); // Output: { price: 100, quantity: 2 }

Error Handling

If the string is not valid JSON, JSON.parse() throws a SyntaxError. Use try...catch for safe parsing:

const invalidJson = '{"name": "Alice", "age": 25,'; // Missing closing brace
try {
    const user = JSON.parse(invalidJson);
} catch (error) {
    console.error("Parsing error:", error.message); // Output: Unexpected end of JSON input
}

Common Use Cases

  • Fetching API Data: Data from APIs often comes as a JSON string, which you can parse into objects:
fetch('https://api.example.com/data')
    .then(response => response.text())
    .then(data => {
        const parsedData = JSON.parse(data);
        console.log(parsedData);
    });
  • Local Storage: Store and retrieve JSON data in localStorage:
const user = { name: "Bob", age: 30 };
localStorage.setItem("user", JSON.stringify(user));

const storedUser = JSON.parse(localStorage.getItem("user"));
console.log(storedUser); // Output: { name: "Bob", age: 30 }

Key Points

  • Always ensure the input string is valid JSON to avoid errors.
  • Use the reviver parameter for advanced transformations during parsing.
  • Be cautious when parsing untrusted JSON strings to avoid potential security issues.

For more JavaScript tutorials, visit The Coding College.

Leave a Comment