How do I fix 'Unexpected end of JSON input' in JavaScript?
Find where the empty string comes from
JSON.parse expects a complete JSON document. If the input is an empty string, an undefined value turned into text, or a response that was cut off, parsing fails with this message. The fastest fix is to log the raw value right before the parse call so you can see exactly what arrived.
Common sources include a fetch call that returned an error page, a file that was saved empty, or a server that closed the connection early. Check the status code and content type before you parse the body. An HTML error page is not JSON, even when you expected data.
- Log the raw value before calling JSON.parse
- Check response status codes first
- Confirm the content type is application/json
- Guard against empty strings with a simple check
Handle bad input safely
Wrap the parse in a try block so the app can show a helpful message instead of crashing. Return a fallback value or ask the user to retry. This keeps one bad response from breaking the whole page.
If the JSON comes from a file, make sure the write finished before another process reads it. Partial writes are a common reason a file looks fine in your editor but fails in code.
Common mistakes
- Parsing the body of a failed request without checking the status first.
- Assuming a file is complete because it exists on disk.

Related questions
- What does NullPointerException mean in Java?
- How do I fix IndexError: list index out of range in Python?
- What does TypeError: 'NoneType' object is not subscriptable mean?
- Why do I get a segmentation fault in C?
- What does ValueError: could not convert string to float mean?
- How do I fix a stack overflow error?