You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React与D3.js报错:JSON解析语法异常及代码问题求助

Fixing "Unexpected token < in JSON at position 0" Error in Your React + D3 App

Let's break down this super common JSON parsing error and get your map app back on track!

Why You're Seeing This Error

That error means your code tried to parse something as JSON, but what it actually got back was HTML content (like a 404 error page, or your app's root HTML file). Since HTML starts with a < character, the JSON parser freaks out and throws that error.

Looking at your code, the most likely culprits are:

  • Incorrect file paths for your JSON/CSV files
  • A misconfigured server that's returning HTML instead of your static data files
  • (Less likely) A syntax error in your JSON files that's making them unparseable

Step-by-Step Fixes

1. Double-Check Your File Paths

First, let's rule out path issues—this is the #1 cause of this error.

  • You're using require("./us-states.json") and require("./us-counties.json"): Make sure these JSON files are in the exact same folder as your App.js. If they're in a subfolder (like data/), update the path to require("./data/us-states.json").
  • In your drawState method, you have queue.defer(d3.csv, './...—that incomplete path is probably pointing to nowhere. For React apps, static files (like CSVs) should either be:
    • Placed in the public folder, then accessed with an absolute path (e.g., '/data/your-file.csv')
    • Imported directly like your JSON files (e.g., import countyData from "./counties.csv"—note: you might need a CSV loader for Webpack if you go this route)

2. Verify the Response in DevTools

Let's confirm what your browser is actually receiving:

  1. Open Chrome/Firefox DevTools (F12 or Ctrl+Shift+I)
  2. Go to the Network tab, then refresh your page
  3. Find the request for your JSON/CSV file (look for the name in the list)
  4. Click on it and check the Response tab:
    • If you see HTML (like <html><body>404 Not Found</body></html>), your path is definitely wrong
    • If you see valid JSON/CSV, then the issue is a syntax error in the file itself

3. Fix JSON Syntax (If Needed)

If the response is valid-looking JSON, run it through a JSON validator to check for:

  • Trailing commas (e.g., {"name": "California", "id": 0,})
  • Unmatched quotes (e.g., {"name": 'California'}—JSON requires double quotes)
  • Missing brackets/parentheses

4. Clean Up Your D3 Queue Usage

Your d3-queue code is incomplete, so make sure you're handling errors properly. Here's a corrected example:

drawState() {
  const queue = d3queue.queue();
  
  queue
    .defer(d3.csv, '/data/your-county-data.csv') // Use correct absolute path
    .await((error, csvData) => {
      if (error) {
        console.error('Failed to load CSV:', error);
        return;
      }
      // Process your CSV data here
    });
}

Bonus: Use ES Modules Instead of require

React works better with ES module syntax, so replace those require calls with imports:

import usState from "./us-states.json";
import usCounty from "./us-counties.json";

Webpack will handle resolving the paths correctly, so you'll get clearer errors if the file is missing.

Example Working Code Snippet

Here's a trimmed-down version of your App that should work (assuming your JSON files are in the same folder):

import React, { Component } from 'react';
import * as d3 from "d3";
import * as topojson from 'topojson';
import usState from "./us-states.json";
import usCounty from "./us-counties.json";

class App extends Component {
  constructor() {
    super();
    this.drawDoc = this.drawDoc.bind(this);
  }

  componentDidMount() {
    this.drawDoc();
  }

  drawDoc() {
    const projection = d3.geoAlbersUsa();
    const path = d3.geoPath().projection(projection);

    // Draw US states
    d3.select("#map-container")
      .append("svg")
      .attr("width", 800)
      .attr("height", 600)
      .selectAll("path")
      .data(topojson.feature(usState, usState.objects.states).features)
      .enter()
      .append("path")
      .attr("d", path)
      .style("fill", "#ccc")
      .style("stroke", "#fff");
  }

  render() {
    return <div id="map-container"></div>;
  }
}

export default App;

内容的提问来源于stack exchange,提问作者Atul kumar singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:25:32