JSON.parse SyntaxError
JavaScript Programming Language
Severity: ModerateWhat Does This Error Mean?
This error means JSON.parse received a string that is not valid JSON. JSON has strict rules — single quotes, trailing commas, and undefined values are all illegal. The error message includes the position in the string where parsing failed.
Affected Models
- Chrome DevTools
- Firefox DevTools
- Node.js
- React
- Vue.js
Common Causes
- The API returned an HTML error page (like a 404 or 500 page) instead of JSON
- Single quotes used instead of double quotes around JSON keys or values
- A trailing comma after the last item in an object or array
- The string contains undefined, NaN, or Infinity — none of which are valid JSON
- The response body was empty or partially received due to a network issue
How to Fix It
-
Log the raw string before parsing to see what you are actually receiving.
console.log(responseText) before JSON.parse(responseText). If it starts with '<', it is HTML, not JSON.
-
Check the HTTP status code of the response.
A 404 or 500 response often returns HTML even if you expected JSON. Check response.ok or response.status before parsing.
-
Wrap JSON.parse in a try-catch to handle errors gracefully.
try { const data = JSON.parse(raw); } catch (e) { console.error('Parse failed:', raw); } — this prevents crashes and gives you the bad input.
-
Validate your JSON string using jsonlint.com before using it in code.
Paste the raw string there. It highlights exactly which character is invalid and why.
-
Use response.json() in the Fetch API instead of manually calling JSON.parse.
fetch(url).then(r => r.json()) handles parsing for you. It still throws on invalid JSON, so keep your try-catch.
When to Call a Professional
If JSON.parse is failing on data from your own API, your backend developer needs to fix the response. If it is failing on a third-party API, check their status page — the API may be returning error pages instead of data.
Frequently Asked Questions
What is valid JSON?
JSON requires double quotes around all strings and keys. Values can be strings, numbers, true, false, null, arrays, or objects. No comments, no trailing commas, no single quotes, no undefined.
Why does my API sometimes return JSON and sometimes return HTML?
Most web servers return an HTML error page for unhandled errors (500) or missing routes (404). Your code should always check the HTTP status code before trying to parse the body as JSON.
How do I convert a JavaScript object back to a JSON string?
Use JSON.stringify(myObject). This always produces valid JSON from a plain object. Note: it will drop any properties set to undefined, since undefined is not a JSON value.