Skip to main content

How to Resolve "SyntaxError: Unexpected end of JSON input" Error in JavaScript

The SyntaxError: Unexpected end of JSON input is a common error that occurs when you try to parse a string with JSON.parse() that is either empty or incomplete. It's the parser's way of saying, "I started to read what I thought was a JSON string, but it ended abruptly before I found a valid JSON value."

This guide will explain the common scenarios where this error occurs—primarily with empty API responses and localStorage—and show you how to correctly handle and prevent it.

The Core Problem: JSON.parse() Requires a Complete JSON String

The JSON.parse() function is very strict. It is designed to convert a valid and complete JSON string into a JavaScript value. An empty string ('') is not a valid JSON document, nor is an incomplete one like {"key":.

Problem: when you pass an empty string to JSON.parse(), it has nothing to parse and immediately throws an error.

// Problem: Passing an empty string to JSON.parse()
let jsonString = '';

// ⛔️ SyntaxError: Unexpected end of JSON input
let result = JSON.parse(jsonString);
note

The key to solving this error is to find out why the string you are trying to parse is empty.

Scenario 1 (Most Common): An Empty Response from an API Call

This is the most frequent cause of the error. Your code makes a request to an API (e.g., with fetch()), expects a JSON response, but the server sends back a response with an empty body.

Example of problem:

async function fetchData() {
try {
// Imagine 'https://api.example.com/api/no-content' returns a 204 No Content status with an empty body.
let response = await fetch('https://api.example.com/api/no-content');

// `response.json()` will fail on an empty body.
// ⛔️ It throws "SyntaxError: Unexpected end of JSON input"
let data = await response.json();

console.log(data);
} catch (error) {
console.error("Failed to parse JSON:", error);
}
}
note

This is common for API endpoints that confirm an action but don't need to return any data (like a DELETE request).

Solution: Check the response status or headers before trying to parse the body.

let response = await fetch('https://api.example.com/api/no-content');

if (response.status === 204) {
// No content to parse, so we can return early.
return;
}

// Only try to parse JSON if there is content.
let data = await response.json();

Scenario 2: An Empty or Missing localStorage Item

Another common cause is trying to parse an item from localStorage that doesn't exist or was stored as an empty string. localStorage.getItem() returns null if the key is not found, and JSON.parse(null) will throw an error.

Example of problem:

// Problem: The 'user-settings' key has never been set.
let settingsString = localStorage.getItem('user-settings');
console.log(settingsString); // # Output: null

// ⛔️ This will throw an error.
let settings = JSON.parse(settingsString);

The Solution: A Robust try...catch Parsing Function

Since the input to JSON.parse() is often unpredictable (coming from an external API or browser storage), the best practice is to always wrap your parsing logic in a way that gracefully handles invalid or empty input.

Solution: this reusable function safely parses a string and returns a default value if the string is empty or parsing fails.

/**
* Safely parses a JSON string.
* @param {string} str The string to parse.
* @param {*} defaultValue The value to return if the string is empty or parsing fails.
* @returns {object | Array | any} The parsed object or the default value.
*/
function safeJsonParse(str, defaultValue) {
// Guard against empty strings, null, or undefined.
if (!str) {
return defaultValue;
}

try {
return JSON.parse(str);
} catch (error) {
return defaultValue;
}
}

// --- Practical Example with localStorage ---
// 1. Retrieve the item from localStorage (it might be null).
let settingsString = localStorage.getItem('user-settings');

// 2. Safely parse it, providing a default empty object `{}`.
let settings = safeJsonParse(settingsString, {});

console.log(settings); // # Output: {} (if the item didn't exist or was empty)
note

This is the most robust and professional way to handle JSON parsing. It prevents your application from crashing due to malformed or missing data.

Conclusion

The SyntaxError: Unexpected end of JSON input is a clear signal that your script is attempting to parse an empty or incomplete string.

  • The root cause is passing an empty string (''), null, or an unfinished JSON string to JSON.parse().
  • This commonly happens when dealing with API responses that might have no body (like a 204 No Content response) or when retrieving a non-existent item from localStorage.
  • The recommended best practice is to guard your parsing logic. Either check your input before parsing or, better yet, wrap all JSON.parse() calls in a try...catch block within a reusable helper function to handle potential errors gracefully and provide a sensible default value.