How to Fix "SyntaxError: JSON.parse" in JavaScript

Published April 2025 · 4 min read

1. API Returned HTML Instead of JSON

// ❌ Server returned error page
const res = await fetch('/api/data');
const data = await res.json(); // SyntaxError!

// ✅ Check response first
const res = await fetch('/api/data');
if (!res.ok) throw new Error('Server error');
const text = await res.text();
console.log(text); // See what you actually got
const data = JSON.parse(text);

2. Double-Parsing

// ❌ Already parsed
const obj = {name: "John"};
JSON.parse(obj); // Error — it's already an object!

// ✅ Check type first
const data = typeof input === 'string' ? JSON.parse(input) : input;

3. BOM Character

// Remove BOM (byte order mark)
const clean = text.replace(/^\uFEFF/, '');
JSON.parse(clean);

4. Safe Parse Wrapper

function safeParse(str) {
  try { return JSON.parse(str); }
  catch (e) { console.error('Invalid JSON:', e.message); return null; }
}

Validate Your JSON

Use our JSON Formatter to find the exact error.

Related