Deep Analysis and Solutions for JSON Parsing Error: Unexpected token < in JSON at position 0 in React

Nov 20, 2025 · Programming · 12 views · 7.8

Keywords: React | JSON Parsing Error | fetch API | HTTP Headers | Error Debugging

Abstract: This article provides an in-depth analysis of the common JSON parsing error 'Unexpected token < in JSON at position 0' in React applications. Through practical code examples, it explains the correct usage of the fetch API, focusing on key solutions such as setting HTTP headers and file path configuration, while offering complete error debugging processes and best practice recommendations.

Problem Phenomenon and Error Analysis

During React application development, developers frequently use the fetch API to retrieve JSON data files. However, a common error occurs when the console outputs Uncaught (in promise) SyntaxError: Unexpected token &lt; in JSON at position 0. This error indicates that the JavaScript engine encountered an unexpected '<' character while parsing JSON data, typically meaning the actual fetched content is not in valid JSON format.

Core Problem Root Causes

By analyzing the original code example:

handleGetJson(){
  console.log("inside handleGetJson");
  fetch(`./fr.json`)
    .then((response) => response.json())
    .then((messages) => {console.log("messages");});
}

The issues primarily stem from several aspects: first, when the server returns non-JSON format data, the response.json() method attempts to parse invalid content; second, the lack of appropriate HTTP headers may cause the server to return HTML error pages instead of the expected JSON data; finally, improper file path configuration can result in 404 errors, with the server returning default HTML pages.

Primary Solution

Based on best practices, the most effective solution is to explicitly set HTTP request headers:

handleGetJson(){
  console.log("inside handleGetJson");
  fetch(`./fr.json`, {
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }
    })
    .then((response) => response.json())
    .then((messages) => {console.log("messages");});
}

By setting both Content-Type and Accept headers to application/json, we explicitly inform the server that the client expects to receive data in JSON format, which helps prevent the server from returning responses in other formats.

Supplementary Solutions

Beyond setting HTTP headers, other important considerations exist. File location configuration is a critical component: in React projects, static files like JSON files should be placed in the public directory rather than the src directory. This is because during the build process, contents of the public directory are directly copied to the output directory, while files in the src directory undergo compilation processing.

Example of proper file structure configuration:

fetch('./data.json').then(response => {
  console.log(response);
  return response.json();
}).then(data => {
  console.log(data);
}).catch(err => {
  console.log("Error Reading data " + err);
});

Error Debugging and Verification Methods

When encountering JSON parsing errors, a systematic debugging process is essential. First, use the response.text() method to inspect the actual fetched content:

const getData = async () => {
  const response = await fetch("/sessions")
  const data = await response.text()
  console.log(data);
}

This approach avoids JSON parsing errors and allows direct viewing of the raw content returned by the server. If the output displays an HTML document (such as containing &lt;!doctype html&gt;), it indicates the request failed to correctly retrieve JSON data.

Deep Understanding of Error Mechanisms

The fundamental cause of this error lies in the working mechanism of the fetch API. When a request fails or the server returns non-JSON content, the response.json() method attempts to parse the response body as JSON. If the response body begins with a '<' character (typically the start of an HTML document), the JSON parser immediately throws a syntax error.

This situation commonly occurs when: the server returns a 404 error page, CORS policies block the request, or file path misconfiguration causes the server to return a default page. Cases from reference articles show that even when using Mock Service Worker (MSW), improper configuration can still result in HTML content being returned instead of the expected JSON data.

Best Practice Recommendations

To completely avoid such errors, adopting the following comprehensive strategy is recommended: always set appropriate HTTP headers; place static resource files in the correct directory structure; implement complete error handling mechanisms; use browser developer tools to monitor network requests and responses during development.

A complete robust code implementation should include:

async handleGetJson() {
  try {
    const response = await fetch('./fr.json', {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const messages = await response.json();
    console.log("Success:", messages);
    return messages;
  } catch (error) {
    console.error("Fetch error:", error);
    // Appropriate error handling logic
  }
}

Conclusion

Although the Unexpected token &lt; in JSON at position 0 error superficially appears as a JSON parsing issue, its underlying causes involve multiple aspects including HTTP request configuration, server response handling, and file path management. By correctly setting HTTP headers, properly configuring file locations, and implementing comprehensive error handling mechanisms, developers can effectively prevent and resolve this issue, ensuring stable and reliable data retrieval functionality in React applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.