React与D3.js报错:JSON解析语法异常及代码问题求助
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")andrequire("./us-counties.json"): Make sure these JSON files are in the exact same folder as yourApp.js. If they're in a subfolder (likedata/), update the path torequire("./data/us-states.json"). - In your
drawStatemethod, you havequeue.defer(d3.csv, './...—that incomplete path is probably pointing to nowhere. For React apps, static files (like CSVs) should either be:- Placed in the
publicfolder, 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)
- Placed in the
2. Verify the Response in DevTools
Let's confirm what your browser is actually receiving:
- Open Chrome/Firefox DevTools (F12 or Ctrl+Shift+I)
- Go to the Network tab, then refresh your page
- Find the request for your JSON/CSV file (look for the name in the list)
- 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
- If you see HTML (like
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

