Unexpected token in JSON

Loading

🚨 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 *