Back to Developer's Study Materials

Fix JSON Errors: Complete Guide

Parse errors, unexpected token <, API returns HTML, JSON.stringify undefined (2026)

What is a JSON Parse Error?

A JSON parse error happens when JSON.parse() gets a string that isn’t valid JSON. "Unexpected token" means the parser hit a character it didn’t expect (e.g. single quote, comma, or < from HTML). JSON allows only double-quoted strings, no trailing commas, and no comments.

Key point: Validate JSON before parsing and use try-catch so your app doesn’t crash.

When Do JSON Errors Happen?

Common cases: parsing API responses (malformed or HTML), user input, localStorage, or files. Also when JSON.stringify drops undefined and you expect the key to be present.

How to Fix: Step-by-Step

1. Fix syntax: trailing commas, quotes, comments

Remove trailing commas, use double quotes for all strings and keys, and remove comments. Example:

// ❌ Invalid
JSON.parse('{"name": "John",}');
// ✅ Valid
JSON.parse('{"name": "John"}');

2. Unexpected token < (API returns HTML)

The error "Unexpected token <" usually means the server returned HTML (e.g. 404 or login page) instead of JSON. Fix: check Content-Type and only parse when it’s JSON:

const res = await fetch(url);
const ct = res.headers.get('content-type');
if (!ct?.includes('application/json')) {
  const text = await res.text();
  throw new Error('Not JSON: ' + text.slice(0, 100));
}
const data = await res.json();

3. JSON.stringify returns undefined / missing keys

JSON.stringify skips properties with value undefined. To keep keys, use a replacer:

const obj = { a: 1, b: undefined };
JSON.stringify(obj); // '{"a":1}' — b is missing

// To output undefined as null:
JSON.stringify(obj, (k, v) => v === undefined ? null : v);
// '{"a":1,"b":null}'

4. Use try-catch and validate

function parseJSONSafe(str) {
  try {
    return { ok: true, data: JSON.parse(str) };
  } catch (e) {
    return { ok: false, error: e.message };
  }
}

Common Error Examples

Trailing comma / single quotes

JSON.parse('{"x": 1,}');  // ❌
JSON.parse('{"x": 1}');   // ✅

API returns HTML

Check Content-Type before parsing. If you get HTML, fix the URL, auth, or server so it returns JSON.

stringify drops undefined

Use a replacer to convert undefined to null if you need the key in the output.

Free tools

Use our JSON Beautifier and JSON Fixer to validate and fix JSON in the browser.

Share this article with Your Friends, Collegue and Team mates

Stay Updated

Get the latest tool updates, new features, and developer tips delivered to your inbox.

No spam. Unsubscribe anytime. We respect your privacy.

Feedback for Fix JSON Errors Guide

Help us improve! Share your thoughts, report bugs, or suggest new features.

Get in Touch

We'd love to hear from you! Write us for any additional feature request, issues, query or appreciation.

Your feedback helps us improve and build better tools for the developer community.