DEV Community

Jitendra
Jitendra

Posted on

Top 2 Strategies for Handling JSON Parse Errors

JSON is quite popular and widely used data format for client and server communication.

JSON Parse

Why do we get a JSON parsing error and How to Resolve Them?

If you have minor issues with JSON data. You can use any online tool such as JSON formatter. Which provides a feature to repair broken JSON.

Parsing JSON is a common task for a developer. JavaScript comes with a built-in method called JSON.parse(). Which is useful for parsing JSON string data.

If JSON is valid then JSON.parse() returns a JSON object otherwise, it throws a SyntaxError.

Handle JSON Parse Error in JavaScript

In JavaScript, There are many ways to deal with JSON parse errors, and we are going to explore two of the best here.

1. Handle Using try-catch block

To deal with JSON parse errors, the try-catch block method is most commonly used in JavaScript.

try {
  const json = '{"name": "Jimmy", "age":28}';
  const obj = JSON.parse(json);
  console.log(obj.name);
  // expected output: "Jimmy"
  console.log(obj.age);
  // expected output: 28
} catch (e) {
  console.log(e);
  // expected output: SyntaxError: Unexpected token o in JSON at position 1
}
Enter fullscreen mode Exit fullscreen mode

2. Handle Using if-else block

Another useful method for handling JSON parse errors is to use an if-else block.
The use of this approach helps when you are doing other tasks in try-catch (for example, API requests and other processing) and then parsing JSON. Using this approach, you may find errors caused by SyntaxError.

try {
    // API calls
    // other handling
    const json = '{"name":"Jimmy", "age:42}';
    const obj = JSON.parse(json);
} catch (error) {
    if (error instanceof SyntaxError) {
        console.log(error);
        // expected output: SyntaxError: Unexpected token o in JSON at position 1
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
shshank profile image
Shshank

nicely written thanks for sharing