Open In App

How to Catch JSON Parse Error in JavaScript ?

JSON (JavaScript Object Notation) is a popular data interchange format used extensively in web development for transmitting data between a server and a client. When working with JSON data in JavaScript, it's common to parse JSON strings into JavaScript objects using the JSON.parse() method. However, parsing JSON data can sometimes lead to errors, especially when the JSON string is malformed or contains unexpected data.

Handling JSON parse errors is crucial for ensuring the stability and reliability of your JavaScript applications. In this article, we'll explore one approach to catch JSON parse errors in JavaScript, along with examples for approach.

Approach: Using try...catch block

This approach involves wrapping the JSON parsing code inside a try...catch block to catch any errors that might occur during parsing.

Syntax:

try {
let parsedData = JSON.parse(jsonString);
} catch (error) {
// Handle the error here
}

Example: In this example, we attempt to parse a JSON string using JSON.parse(). If an error occurs during parsing, it will be caught by the catch block and handled accordingly.

let jsonString = '{"name": "GFG", "age": 22}';
try {
    let parsedData = JSON.parse(jsonString);
    console.log(parsedData);
} catch (error) {
    console.error('Error parsing JSON:', error);
}

Output

{name: "GFG", age: 22}
Article Tags :