Unexpected token in JSON

๐Ÿšจ Unexpected Token in JSON โ€“ JavaScript Error Explained ๐Ÿšจ


๐Ÿ“Œ Introduction

The “Unexpected token in JSON” error occurs when parsing JSON data using JSON.parse() in JavaScript. This happens when the JSON string is incorrectly formatted, has extra or missing characters, or is not valid JSON.

๐Ÿš€ What Youโ€™ll Learn

โœ”๏ธ What causes the Unexpected token in JSON error?
โœ”๏ธ Common mistakes leading to the error
โœ”๏ธ Step-by-step debugging process
โœ”๏ธ Best practices to avoid the error


1๏ธโƒฃ Understanding JSON Parsing

JSON (JavaScript Object Notation) is a lightweight format for storing and transporting data.

โœ… Correct JSON Example

{
  "name": "John",
  "age": 30,
  "city": "New York"
}

To parse JSON in JavaScript:

const jsonString = '{"name":"John","age":30,"city":"New York"}';
const obj = JSON.parse(jsonString); // โœ… Successfully parsed
console.log(obj.name); // Output: John

๐Ÿ”น JSON.parse() converts a JSON string into a JavaScript object.
๐Ÿ”น If the JSON format is incorrect, a SyntaxError will be thrown.


2๏ธโƒฃ Common Causes of “Unexpected Token in JSON”

๐Ÿ”ด 1. Extra Comma at the End

โŒ Incorrect JSON (Trailing Comma)

{
  "name": "John",
  "age": 30,
}

๐Ÿ”ด Error Message:

SyntaxError: Unexpected token } in JSON

โœ”๏ธ Fix: Remove the Extra Comma

{
  "name": "John",
  "age": 30
}

๐Ÿ”ด 2. JSON String is Not Properly Formatted

โŒ Incorrect JSON (Single Quotes)

const jsonString = '{'name': 'John', 'age': 30}'; 
JSON.parse(jsonString); 

๐Ÿ”ด Error Message:

SyntaxError: Unexpected token ' in JSON

โœ”๏ธ Fix: Use Double Quotes

const jsonString = '{"name": "John", "age": 30}';
JSON.parse(jsonString);

๐Ÿ”ด 3. JSON Contains Undefined or Functions

โŒ Incorrect JSON

const jsonString = '{"name": "John", "age": undefined}';
JSON.parse(jsonString);

๐Ÿ”ด Error Message:

SyntaxError: Unexpected token u in JSON

โœ”๏ธ Fix: Remove undefined (JSON Only Supports null)

const jsonString = '{"name": "John", "age": null}';
JSON.parse(jsonString);

๐Ÿ”ด 4. Using JSON.stringify() Incorrectly

โŒ Incorrect JSON Conversion

const obj = { name: "John", age: 30, greet: function() { return "Hello"; } };
const jsonString = JSON.stringify(obj);
console.log(jsonString); 

โœ”๏ธ Fix: Remove Functions Before Converting

const obj = { name: "John", age: 30 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // โœ… {"name":"John","age":30}

๐Ÿ”ด 5. Malformed JSON from API Response

Sometimes, an API returns invalid JSON.

Example: Fetching Incorrect JSON

fetch("https://api.example.com/user")
  .then(response => response.text()) // Getting response as text
  .then(data => {
    console.log(JSON.parse(data)); // โŒ May cause error
  })
  .catch(error => console.error(error));

โœ”๏ธ Fix: Validate Response Before Parsing

fetch("https://api.example.com/user")
  .then(response => response.json()) // โœ… Directly parse as JSON
  .then(data => console.log(data))
  .catch(error => console.error("Invalid JSON:", error));

3๏ธโƒฃ Debugging & Fixing JSON Errors

๐Ÿ”น 1. Check JSON Format with an Online Validator

Use JSONLint (jsonlint.com) to validate JSON format.


๐Ÿ”น 2. Use Try-Catch to Handle Errors

const jsonString = '{"name": "John", "age": 30}';

try {
  const obj = JSON.parse(jsonString);
  console.log(obj);
} catch (error) {
  console.error("Invalid JSON:", error.message);
}

๐Ÿ”น Prevents the program from crashing when an invalid JSON is parsed.


๐Ÿ”น 3. Ensure Proper JSON Formatting

โœ”๏ธ Use double quotes for keys and string values.
โœ”๏ธ Avoid trailing commas.
โœ”๏ธ Replace undefined with null.
โœ”๏ธ Do not include functions in JSON.


4๏ธโƒฃ Summary

๐Ÿ”น Cause๐Ÿ”น Error๐Ÿ”น Solution
Extra commaUnexpected token } in JSONRemove the trailing comma
Single quotes instead of doubleUnexpected token ' in JSONUse double quotes (" ")
Undefined valuesUnexpected token u in JSONReplace with null
Functions inside JSONUnexpected token f in JSONRemove functions before JSON.stringify()
Malformed API responseUnexpected token < in JSONValidate API response before parsing

๐ŸŽฏ Best Practices

โœ… Use JSONLint to validate JSON
โœ… Wrap JSON.parse() in a try-catch block
โœ… Ensure API responses are valid JSON
โœ… Never use single quotes for JSON strings
โœ… Avoid using undefined and functions in JSON


๐ŸŽ‰ Now You Know How to Handle Unexpected Token in JSON!

Would you like more examples or debugging techniques? Let me know!

Leave a Reply

Your email address will not be published. Required fields are marked *