Tutorials Logic, IN info@tutorialslogic.com

JSON.parse unexpected token: Tutorial, Examples, FAQs & Interview Tips

JSON.parse unexpected token

json_parse_error is an important JavaScript topic because it shows up in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.

Focus on what problem json_parse_error solves, where developers usually make mistakes, and how to verify the result with output, behavior, or a small test.

A strong understanding of json_parse_error should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work.

JSON.parse unexpected token should be studied as a practical JavaScript lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the javascript > errors > json-parse-error page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

What is JSON.parse Error?

The error SyntaxError: Unexpected token in JSON occurs when JSON.parse() receives invalid JSON data. JSON must follow strict formatting rules, and any deviation causes this error.

Common Causes

  • Parsing non-JSON string (HTML, plain text, etc.)
  • Single quotes instead of double quotes
  • Trailing commas in JSON
  • Undefined or function values in JSON
  • Parsing already-parsed object

Quick Fix (TL;DR)

Quick Solution

Quick Solution
// [wrong] Problem - Invalid JSON
JSON.parse("{'name': 'John'}"); // Single quotes - Error!

// [ok] Solution - Valid JSON with double quotes
JSON.parse('{"name": "John"}'); // Works!

// [ok] Solution - Use try-catch
try {
    const data = JSON.parse(jsonString);
    console.log(data);
} catch (error) {
    console.error('Invalid JSON:', error);
}

Common Scenarios & Solutions

JSON requires double quotes for strings. Single quotes are not valid JSON.

Trying to parse an object that's already a JavaScript object, not a JSON string.

JSON doesn't allow trailing commas, unlike JavaScript objects.

Trying to parse non-JSON content like HTML error pages or plain text.

JSON doesn't support undefined, functions, or other JavaScript-specific types.

Problem

Problem
// Invalid JSON - single quotes
const jsonString = "{'name': 'John', 'age': 30}";
JSON.parse(jsonString); // SyntaxError!

// Also invalid - unquoted keys
const jsonString2 = "{name: 'John'}";
JSON.parse(jsonString2); // SyntaxError!

Solution

Solution
// Valid JSON - double quotes for both keys and values
const jsonString = '{"name": "John", "age": 30}';
const data = JSON.parse(jsonString);
console.log(data); // { name: 'John', age: 30 }

// Or use template literals with double quotes inside
const jsonString2 = `{"name": "John", "age": 30}`;
const data2 = JSON.parse(jsonString2);

Problem

Problem
// Already a JavaScript object
const user = { name: 'John', age: 30 };
JSON.parse(user); // SyntaxError: Unexpected token o in JSON

// Or from API that already returns object
fetch('/api/user')
    .then(res => res.json()) // Already parsed here
    .then(data => {
        const parsed = JSON.parse(data); // Error! Already an object
    });

Solution

Solution
// Don't parse if already an object
const user = { name: 'John', age: 30 };
console.log(user); // Use directly

// Check type before parsing
function safeParse(data) {
    if (typeof data === 'string') {
        return JSON.parse(data);
    }
    return data; // Already an object
}

// With fetch, don't double-parse
fetch('/api/user')
    .then(res => res.json()) // Parse once
    .then(data => {
        console.log(data); // Use directly, don't parse again
    });

Problem

Problem
// Trailing comma in object
const jsonString = '{"name": "John", "age": 30,}';
JSON.parse(jsonString); // SyntaxError!

// Trailing comma in array
const jsonString2 = '["apple", "banana", "orange",]';
JSON.parse(jsonString2); // SyntaxError!

Solution

Solution
// Remove trailing commas
const jsonString = '{"name": "John", "age": 30}'; // No trailing comma
JSON.parse(jsonString); // Works!

const jsonString2 = '["apple", "banana", "orange"]'; // No trailing comma
JSON.parse(jsonString2); // Works!

// Or clean the string before parsing
function cleanJSON(str) {
    return str.replace(/,(\s*[}\]])/g, '$1'); // Remove trailing commas
}

const dirty = '{"name": "John",}';
const clean = cleanJSON(dirty);
JSON.parse(clean); // Works!

Problem

Problem
// API returns HTML error page instead of JSON
fetch('/api/user')
    .then(res => res.json()) // Tries to parse HTML as JSON
    .then(data => console.log(data))
    .catch(err => console.error(err)); // SyntaxError!

// Or plain text response
const response = "User not found";
JSON.parse(response); // SyntaxError!

Solution

Solution
// Check content type before parsing
fetch('/api/user')
    .then(res => {
        const contentType = res.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
            return res.json();
        } else {
            return res.text(); // Get as text instead
        }
    })
    .then(data => console.log(data))
    .catch(err => console.error(err));

// Or check if response is OK
fetch('/api/user')
    .then(res => {
        if (!res.ok) {
            throw new Error(`HTTP error! status: ${res.status}`);
        }
        return res.json();
    })
    .then(data => console.log(data))
    .catch(err => console.error(err));

// Use try-catch for manual parsing
function safeParse(str) {
    try {
        return JSON.parse(str);
    } catch (error) {
        console.error('Not valid JSON:', str);
        return null;
    }
}

Problem

Problem
// Trying to stringify and parse undefined
const obj = { name: 'John', age: undefined };
const jsonString = JSON.stringify(obj); // '{"name":"John"}' - age is omitted
console.log(jsonString);

// Function in object
const obj2 = {
    name: 'John',
    greet: function() { return 'Hello'; }
};
const jsonString2 = JSON.stringify(obj2); // '{"name":"John"}' - function omitted

Solution

Solution
// Use null instead of undefined
const obj = { name: 'John', age: null };
const jsonString = JSON.stringify(obj);
const parsed = JSON.parse(jsonString); // Works!

// Remove undefined values before stringifying
function cleanObject(obj) {
    return Object.fromEntries(
        Object.entries(obj).filter(([_, v]) => v !== undefined)
    );
}

const obj2 = { name: 'John', age: undefined, city: 'NYC' };
const clean = cleanObject(obj2);
const jsonString2 = JSON.stringify(clean); // '{"name":"John","city":"NYC"}'

// Use replacer function
const obj3 = { name: 'John', age: undefined };
const jsonString3 = JSON.stringify(obj3, (key, value) => {
    return value === undefined ? null : value;
});

Best Practices

  • Always use try-catch - Wrap JSON.parse() in try-catch blocks
  • Validate JSON format - Use double quotes, no trailing commas
  • Check content type - Verify response is JSON before parsing
  • Don't double-parse - Check if data is already an object
  • Use JSON validators - Test JSON with online validators
  • Handle errors gracefully - Provide fallback values
  • Log the input - Console.log the string before parsing for debugging

Related Errors

JSON.parse unexpected token in Real Work

JSON.parse unexpected token matters in JavaScript because it changes how a program is written, tested, or debugged. The page should explain the normal flow first: what the developer writes, what the runtime or platform does, and what result should appear.

When teaching JSON.parse unexpected token, avoid stopping at syntax. Show the surrounding decision: why this feature is chosen, what problem it removes, and what would become harder if the feature were not used.

  • Identify the concrete problem solved by JSON.parse unexpected token.
  • Show the normal input, operation, and output for json.
  • Mention the nearby alternative a beginner may confuse with this topic.
  • Tie the explanation to a real project task, command, component, query, or debugging step.

JSON.parse unexpected token Java review example

JSON.parse unexpected token Java review example
class JSONparseunexpectedtokenReview {
    public static void main(String[] args) {
        String state = "ready";
        System.out.println("JSON.parse unexpected token: " + state);
    }
}

JSON.parse unexpected token guard example

JSON.parse unexpected token guard example
String value = null;
if (value == null) {
    System.out.println("JSON.parse unexpected token: handle the missing value before continuing");
}
Key Takeaways
  • Explain the purpose of json_parse_error before memorizing syntax.
  • Trace the exact call expression and confirm which value reached the parentheses.
  • Test one normal case, one edge case, and one mistake case for json_parse_error.
  • Write down why the value is not callable and what should hold the function instead.
  • Connect json_parse_error to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Calling a value before checking whether it actually holds a function reference.
RIGHT Trace the variable assignment, the property lookup, and the actual call expression.
Most beginner errors come from skipping the behavior behind the syntax.
WRONG Memorizing JSON.parse unexpected token without the situation where it is useful.
RIGHT Connect JSON.parse unexpected token to a concrete JavaScript task.
Purpose makes syntax easier to recall.
WRONG Testing JSON.parse unexpected token only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Memorizing JSON.parse unexpected token without the situation where it is useful.
RIGHT Connect JSON.parse unexpected token to a concrete JavaScript task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it guards with `typeof` or uses the correct method name.
  • Write one mistake related to json_parse_error, then fix it and explain the fix.
  • Summarize when to use json_parse_error and when another approach is better.
  • Write a small example that uses JSON.parse unexpected token in a realistic JavaScript scenario.
  • Change one important value in the JSON.parse unexpected token example and predict the result first.

Frequently Asked Questions

JSON.parse() throws an error when the input string is not valid JSON. Common causes include single quotes instead of double quotes, trailing commas, parsing already-parsed objects, or trying to parse HTML/plain text.

Use double quotes for all strings, remove trailing commas, wrap in try-catch, check if data is already an object, and validate the JSON format before parsing.

JSON specification requires double quotes for strings. Single quotes are not valid JSON, even though they work in JavaScript objects. Always use double quotes in JSON.

Wrap JSON.parse() in a try-catch block, check the content type of API responses, validate the JSON format, and provide fallback values for parse errors.

Valid JSON uses double quotes for strings, no trailing commas, no undefined values, no functions, and no comments. Keys must be strings in double quotes.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.