JSON ( JavaScript Object Notation), is widely used format for asynchronous communication between webpage or mobile application to back-end servers. Due to increasing trend in Single Page Application or Mobile Application, popularity of the JSON is extreme.

Why do we get JSON parse error?

Parsing JSON is a very common task in JavaScript. JSON.parse() is a built-in method in JavaScript which is used to parse a JSON string and convert it into a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true

How to handle JSON parse error?

There are many ways to handle JSON parse error. In this post, I will show you how to handle JSON parse error in JavaScript.

1. Using try-catch block

The most common way to handle JSON parse error is using try-catch block. If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.

try {
  const json = '{"result":true, "count":42}';
  const obj = JSON.parse(json);
  console.log(obj.count);
  // expected output: 42
  console.log(obj.result);
  // expected output: true
} catch (e) {
  console.log(e);
  // expected output: SyntaxError: Unexpected token o in JSON at position 1
}

2. Using if-else block

Another way to handle JSON parse error is using if-else block.

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
if (obj instanceof SyntaxError) {
  console.log(obj);
  // expected output: SyntaxError: Unexpected token o in JSON at position 1
} else {
  console.log(obj.count);
  // expected output: 42
  console.log(obj.result);
  // expected output: true
}

3. Using try-catch block with JSON.parse()

The third way to handle JSON parse error is using try-catch block with JSON.parse().

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json, (key, value) => {
  try {
    return JSON.parse(value);
  } catch (e) {
    return value;
  }
});
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true

4. Using try-catch block with JSON.parse() and JSON.stringify()

The fourth way to handle JSON parse error is using try-catch block with JSON.parse() and JSON.stringify(). If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will return a SyntaxError.

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json, (key, value) => {
  try {
    return JSON.parse(value);
  } catch (e) {
    return value;
  }
});
const str = JSON.stringify(obj);
console.log(str);
// expected output: {"result":true,"count":42}