使用d3.js读取非标准JSON格式文件的技术求助
Hey there! I see you're hitting a snag trying to load that JSON file with D3.js—let's get this sorted out.
First off, you're totally right about D3 expecting a valid JSON array (or a single top-level object) for d3.json() to work properly. The problem with your current file is that it's two separate JSON objects mashed together without wrapping them in an array or separating them correctly, which makes it invalid JSON overall. JSON specs only allow one top-level value (either an object or an array), so that's why D3 can't parse it out of the box.
Solution 1: Modify the Original JSON File (Easiest if Possible)
If you have control over the source file, just reformat it into a proper JSON array like you mentioned:
[ {"name":"Andy Hunt", "title":"Big Boss", "age": 68, "bonus": true }, {"name":"Charles Mack", "title":"Jr Dev", "age":24, "bonus": false } ]
Once you do this, d3.json("your-file.json") will work exactly as you expect, returning the array of objects you need.
Solution 2: Process Raw Text If You Can't Edit the File
If you can't modify the original JSON (say it's generated by a system you don't control), use d3.text() to load the raw content first, then clean it up into valid JSON manually:
d3.text("your-file.json") .then(rawText => { // Split the raw text into individual object strings const objectChunks = rawText.split(/}\s*{/); // Fix the braces on each chunk and parse into JSON objects const parsedData = objectChunks.map(chunk => { let fixedChunk = chunk; if (!fixedChunk.startsWith("{")) fixedChunk = "{" + fixedChunk; if (!fixedChunk.endsWith("}")) fixedChunk = fixedChunk + "}"; return JSON.parse(fixedChunk); }); // Now parsedData is your array of objects—use it in your D3 code! console.log(parsedData); // Example: Bind data to elements d3.select("body") .selectAll("div") .data(parsedData) .enter() .append("div") .text(d => `${d.name} - ${d.title}`); }) .catch(error => { console.error("Oops, something went wrong:", error); });
This approach splits the raw text at the boundary between your two objects, fixes the missing braces on the first and last chunks, then parses each one into a JavaScript object. The end result is the array D3 needs to work with.
Just a quick note: This method assumes your JSON objects don't contain } followed by { inside their values (like in a string). If they do, you might need a more robust regex or a custom parser, but for simple cases like your example, this works perfectly.
内容的提问来源于stack exchange,提问作者ChrisW

