The error "Unexpected end of JSON input" occurs when a JSON parser (commonly JSON.parse in JavaScript) expects more data but reaches the end of the input. Typical causes are truncated responses, network issues, or trying to parse an empty string.
Steps to diagnose and fix:
1. Verify the raw input: Log the exact string being parsed to confirm it's valid JSON and not empty or cut off.
2. Check the producer: Ensure the server or process generating the JSON returns a complete, well-formed JSON document and sets the correct content length or uses chunked transfer properly.
3. Handle empty responses: Before parsing, confirm the string is non-empty. For example, if an HTTP request can legitimately return an empty body, handle that case explicitly instead of calling JSON.parse.
4. Validate with a linter: Paste the response into a JSON validator or use a schema validator (JSON Schema) to catch structural issues.
5. Add robust error handling: Wrap JSON.parse in try/catch and surface informative diagnostics (raw payload, headers, status codes) to speed debugging.
Example checks:
- If using fetch in JavaScript, prefer response.json() which rejects for invalid JSON; if using response.text(), inspect the text before parsing.
- Check for stray characters (like partial HTML error pages) that make the payload invalid JSON.
Following these steps will help you locate whether the issue is on the client (parsing of an empty or partial string) or the server (sending incomplete or non-JSON content) and apply the appropriate fix.