SyntaxError: Unexpected end of JSON input
SyntaxError: Unexpected end of JSON input in JavaScript means jSON.parse() or response.json() was given text that ended too early. Most often the text was completely empty: an empty server response, an empty input box or an empty stored value.
How do I fix SyntaxError: Unexpected end of JSON input?
SyntaxError: Unexpected end of JSON input means JSON.parse() or response.json() got text that ended too early, usually an empty string. A common cause is a 204 No Content response or an empty input box. Read the body with await res.text() first, and only call JSON.parse(text) when text is not empty.
- 1. Log the raw textconsole.log(JSON.stringify(text)) before parsing. If it prints "", there was nothing to parse.
- 2. Check the responseIn the browser Network tab, look at the status and body. 204 and many errors have no body.
- 3. Guard empty stringsUse text ? JSON.parse(text) : null, and wrap JSON.parse in try/catch for stored or user input.
What does SyntaxError: Unexpected end of JSON input mean?
JSON.parse reads text and expects a complete value such as {...} or [...]. If the text is empty, or stops halfway (like '{"name":'), it runs out of characters and throws this error. It never tells you which string was empty, so you have to log it. Note: JSON.parse(null) does not throw (it returns null), but JSON.parse("") does.
Why does SyntaxError: Unexpected end of JSON input happen?
1. The server sent an empty body
Responses like 204 No Content, or some error responses, have no body, but res.json() tries to parse it anyway.
Breaks
const res = await fetch("/api/item/1", { method: "DELETE" });
const data = await res.json();Works
const res = await fetch("/api/item/1", { method: "DELETE" });
const text = await res.text();
const data = text ? JSON.parse(text) : null;2. Parsing an empty string
An empty input box, or a value saved as "", has nothing to parse.
Breaks
const settings = JSON.parse(input.value);Works
const settings = input.value.trim()
? JSON.parse(input.value)
: {};3. Text that was cut off
A string built by hand, or a file that was not fully written, ends before the closing } or ].
Breaks
JSON.parse('{"name": "Ada", "age":');Works
JSON.parse('{"name": "Ada", "age": 36}');How to find it in your own code
Checklist: 1) Log the text right before parsing: console.log(JSON.stringify(text)) shows "" clearly. 2) For fetch, use res.text() first and check res.status in the Network tab. 3) Only parse when the text is not empty. 4) Wrap JSON.parse in try/catch when the text comes from users or storage, and fall back to a default value.
Practise type errors
None of the challenges raises this exact error yet. These practise the same kind of bug.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.