Back to JavaScript
2026-02-159 min read

SyntaxError: JSON.parse: bad parsing (JavaScript)

Learn SyntaxError: JSON.parse: bad parsing (JavaScript) step by step with clear examples and exercises.

Why This Matters

In this full guide, we delve deep into the common error SyntaxError: JSON.parse: bad parsing that developers often encounter while working with JavaScript and JSON data. We will provide practical examples, debugging tips, and insights to help you understand why this matters, how to avoid it, and what to do when it happens.

Why This Matters

Understanding the SyntaxError: JSON.parse: bad parsing error is crucial for several reasons:

  1. Debugging: When working with JSON data in JavaScript, this error can cause frustration as it prevents your code from executing correctly. Identifying and fixing the root cause of this issue will help you become a more efficient developer.
  2. Interviews and Exams: This topic is often covered in technical interviews and exams to test your understanding of JSON parsing and JavaScript syntax. Being well-versed in this error will give you an edge in such situations.
  3. Real-world scenarios: You may encounter this issue when working on projects that involve fetching data from APIs or storing data as JSON files. Knowing how to handle this error will help ensure a smoother development process.
  4. Error handling and best practices: Mastering the SyntaxError: JSON.parse: bad parsing error helps you develop robust code by implementing proper error handling techniques and following best practices for working with JSON data in JavaScript.

Prerequisites

To fully grasp the concepts in this lesson, you should have a basic understanding of:

  1. JavaScript syntax and variables
  2. JSON (JavaScript Object Notation) data format
  3. The JSON.parse() method in JavaScript
  4. Basic error handling techniques in JavaScript
  5. Understanding the structure of objects, arrays, and strings in both JSON and JavaScript

Core Concept

The SyntaxError: JSON.parse: bad parsing error occurs when the provided string is not a valid JSON object, making it impossible for the JSON.parse() method to successfully parse the data. This can happen due to various reasons such as missing or extra characters, incorrect syntax, or invalid Unicode escapes.

JSON Syntax

A valid JSON object should adhere to the following rules:

  1. It must be a string enclosed in double quotes (").
  2. The objects are composed of key-value pairs separated by a colon (:).
  3. Each key is a string, and each value can be a string, number, boolean, null, array, or another JSON object.
  4. Keys must be unique within an object.
  5. Objects are enclosed in curly braces ({}).
  6. Arrays are enclosed in square brackets ([]) and contain comma-separated values.
  7. Strings can include escape sequences to represent special characters, such as \n for a newline or \" for a double quote.
  8. Numbers can be represented in decimal, hexadecimal (with the prefix 0x), or binary (with the prefix 0b) formats.

The JSON.parse() method

The JSON.parse() method is used to convert a JSON string into a JavaScript object. It takes one argument, the JSON string, and returns the parsed JavaScript object.

const jsonString = '{"name": "John", "age": 30, "hobbies": ["reading", "gaming"]}';
const parsedObject = JSON.parse(jsonString);
console.log(parsedObject); // { name: 'John', age: 30, hobbies: [ 'reading', 'gaming' ] }

Common JSON issues causing SyntaxError: JSON.parse: bad parsing

  1. Missing or extra quotes: Ensure that all keys and values in the JSON string are enclosed in double quotes and that the entire string is also properly quoted.
  2. Incorrect syntax: Check for missing commas, curly braces, square brackets, and colons in your JSON strings.
  3. Invalid Unicode escapes: Use valid Unicode escapes (e.g., \u0061 for the letter 'a') when necessary to ensure that special characters are properly represented in your JSON string.
  4. Using JSON.parse() on non-JSON data: Be careful not to pass non-JSON strings or objects to JSON.parse(), as it will throw an error.
  5. Forgetting to handle errors: Always include a try-catch block when using JSON.parse() to handle potential errors gracefully and provide fallback actions if necessary.
  6. Incorrect JSON structure: Check for invalid structures, such as objects within arrays or vice versa, or incorrectly nested objects and arrays.
  7. Using outdated browsers: Some older browsers may not support certain JSON features, leading to parsing errors. Ensure that you are using a modern browser or transpile your code using tools like Babel.
  8. Incorrect data types: Make sure that the values in your JSON objects are compatible with their corresponding keys (e.g., numbers for numeric keys and strings for string keys).
  9. Circular references: Circular references in JSON objects can cause parsing errors. To avoid this, break the circular reference before parsing or use libraries like json-stable-stringify to handle circular references gracefully.
  10. Incorrectly formatted dates: Dates in JSON should be represented as strings with a specific format (e.g., YYYY-MM-DDTHH:mm:ss.sssZ). Make sure that your date strings are properly formatted when parsing them using JSON.parse().
  11. Incorrectly formatted Booleans: Boolean values in JSON should be represented as either true or false. Ensure that your Boolean values are correctly spelled and case-sensitive.
  12. Incorrectly formatted null values: The null value in JSON should be represented as the keyword null. Make sure that your null values are properly represented when parsing them using JSON.parse().

Worked Example

Let's consider a scenario where we fetch data from an API and try to parse it using JSON.parse(). If the response is not properly formatted, we may encounter the SyntaxError: JSON.parse: bad parsing error.

fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));

If the API returns an invalid JSON string, such as:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

This indicates that the provided JSON string is not valid and cannot be parsed by JSON.parse(). To handle this error, we can add a try-catch block to catch the exception and provide a fallback or alternative action.

fetch('https://api.example.com/data')
.then(response => response.text())
.then(text => {
try {
const data = JSON.parse(text);
console.log(data);
} catch (error) {
console.error('Invalid JSON:', error);
// Add a fallback action, such as using a default object or fetching data from another source
}
});

Common Mistakes

  1. Missing or extra quotes: Ensure that all keys and values in the JSON string are enclosed in double quotes and that the entire string is also properly quoted.
  2. Incorrect syntax: Check for missing commas, curly braces, square brackets, and colons in your JSON strings.
  3. Invalid Unicode escapes: Use valid Unicode escapes (e.g., \u0061 for the letter 'a') when necessary to ensure that special characters are properly represented in your JSON string.
  4. Using JSON.parse() on non-JSON data: Be careful not to pass non-JSON strings or objects to JSON.parse(), as it will throw an error.
  5. Forgetting to handle errors: Always include a try-catch block when using JSON.parse() to handle potential errors gracefully and provide fallback actions if necessary.
  6. Incorrect JSON structure: Check for invalid structures, such as objects within arrays or vice versa, or incorrectly nested objects and arrays.
  7. Using outdated browsers: Some older browsers may not support certain JSON features, leading to parsing errors. Ensure that you are using a modern browser or transpile your code using tools like Babel.
  8. Incorrect data types: Make sure that the values in your JSON objects are compatible with their corresponding keys (e.g., numbers for numeric keys and strings for string keys).
  9. Circular references: Circular references in JSON objects can cause parsing errors. To avoid this, break the circular reference before parsing or use libraries like json-stable-stringify to handle circular references gracefully.
  10. Incorrectly formatted dates: Dates in JSON should be represented as strings with a specific format (e.g., YYYY-MM-DDTHH:mm:ss.sssZ). Make sure that your date strings are properly formatted when parsing them using JSON.parse().
  11. Incorrectly formatted Booleans: Boolean values in JSON should be represented as either true or false. Ensure that your Boolean values are correctly spelled and case-sensitive.
  12. Incorrectly formatted null values: The null value in JSON should be represented as the keyword null. Make sure that your null values are properly represented when parsing them using JSON.parse().
  13. Using JSON.stringify() on non-serializable objects or values: Be careful not to pass non-serializable objects or values (e.g., functions, cycles, etc.) to JSON.stringify(), as it will throw an error or produce unexpected results.
  14. Forgetting to handle errors when using JSON.stringify(): Always include a try-catch block when using JSON.stringify() to handle potential errors gracefully and provide fallback actions if necessary.

Practice Questions

  1. Given the following JSON string:
const jsonString = '{"name": "John", "age": 30, hobbies: ["reading", "gaming"]}';

const parsedObject = JSON.parse(jsonString);
console.log(parsedObject.hobbies[1]); // What will be logged?
  1. Write a function to validate if a given string is a valid JSON object or not.
  2. Given the following JavaScript object:
const data = { name: 'John', age: 30, hobbies: ['reading', 'gaming'] };
const jsonString = JSON.stringify(data);
console.log(jsonString); // Output: {"name":"John","age":30,"hobbies":["reading","gaming"]}

What will be logged if we call JSON.parse() on the resulting jsonString?

  1. Write a function to convert a JavaScript object into a JSON string, while handling circular references gracefully using the json-stable-stringify library.
  2. Given the following JSON string:
const jsonString = '{"name": "John", "age": 30, "hobbies": ["reading", "gaming"], "books": [1, 2, 3]}';

const parsedObject = JSON.parse(jsonString);
console.log(parsedObject.books[2]); // What will be logged?

FAQ

Q: Why does the JSON.parse() method throw an error for invalid JSON strings?

A: The JSON.parse() method checks for a valid JSON structure and throws an exception (SyntaxError) if it encounters any issues, such as missing or extra characters, incorrect syntax, or invalid Unicode escapes. This helps ensure that your code doesn't unintentionally execute with corrupted data.

Q: How can I debug the SyntaxError: JSON.parse: bad parsing error?

A: To debug this error, you can use a try-catch block to catch the exception and log the error message for further inspection. You can also manually inspect the JSON string or use online tools like JSONLint (https://jsonlint.com/) to validate its structure before using it with JSON.parse().

Q: What is the difference between JSON.stringify() and JSON.parse()?

A: JSON.stringify() converts a JavaScript object or value into a JSON string, while JSON.parse() does the opposite by parsing a JSON string into a JavaScript object. Both methods are essential for working with JSON data in JavaScript.

Q: How can I handle circular references when using JSON.stringify() and JSON.parse()?

A: To handle circular references when using JSON.stringify(), you can use libraries like json-stable-stringify or manually break the circular reference before serializing the object. When parsing JSON data with circular references, you may encounter errors or unexpected results. In such cases, consider handling circular references gracefully by ignoring them or providing default values.

Q: How can I validate a JSON string without using JSON.parse()?

A: You can

SyntaxError: JSON.parse: bad parsing (JavaScript) | JavaScript | XQA Learn