Firefox控制台JSON.parse遇空字符串报错的解决方法
解决JSON.parse语法错误及JSON空值处理问题
错误原因分析
你遇到的Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1错误,通常由以下几种情况导致:
- JSON文件格式不合法:开头存在非JSON字符(如空格、BOM头、注释),或者4164行的空值键值对写法错误(比如写成
"key": ,而非"key": null) - 文件路径错误:
./data/trueData.json路径不正确,d3请求到的不是有效JSON内容(比如返回404页面、HTML文本) - 服务器配置问题:本地服务器未正确返回JSON文件,导致响应内容不是纯JSON
解决方案
1. 校验并修复JSON文件
- 使用JSON校验工具检查文件,重点确认:
- 文件开头无多余字符(比如BOM头、空格)
- 所有空值键值对符合JSON规范:空值必须写为
"key": null,不能省略值或写为空字符串(除非业务允许) - 4164行的空值条目没有语法错误(比如缺少逗号、引号不闭合)
2. 验证文件路径与响应内容
- 在浏览器地址栏直接访问
./data/trueData.json,确认能返回纯JSON内容 - 在d3请求中添加错误捕获,查看实际返回的内容:
d3.json("./data/trueData.json") .then(function(data) { // 原有处理逻辑 }) .catch(function(error) { console.error("JSON加载失败:", error); // 打印实际返回的文本,排查问题 fetch("./data/trueData.json") .then(res => res.text()) .then(rawText => console.log("服务器返回内容:", rawText)); });
3. 代码逻辑修正
你的代码还有几个潜在问题,需要同步修复:
- 错误的GeoJSON链接:
let link = 'https://geojson.io/#map=4.08/39.3/-97.79'是网页链接,不是GeoJSON数据接口,需要替换为实际的GeoJSON数据URL(比如geojson.io导出的原始数据地址) - 循环逻辑错误:内层
for(let n in data)嵌套在外层循环中,会导致重复执行数万次,严重影响性能;且chooseColor函数定义在循环内部,每次循环都会重新创建,应移到循环外部 - 变量赋值顺序错误:
lngDifference = regionLngArray - countyAbs中,regionLngArray和countyAbs的赋值在计算之后,导致计算时变量未初始化 - 属性访问风险:
feature.Malden.RegionName未做存在性判断,若feature.Malden不存在会直接报错,应改为feature?.Malden?.RegionName(可选链操作符)
修正后的核心代码示例:
// 把chooseColor移到循环外 function chooseColor(lngDifference){ if (lngDifference < 0.0025) return "purple"; else if (lngDifference < 0.005) return "green"; else if (lngDifference < 0.05) return "orange"; else if (lngDifference < 0.5) return "red"; else if (lngDifference < 1) return "Yellow"; else return "black"; } d3.json("./data/trueData.json") .then(function(data) { let regionNameVar2; let regionLatVar2; let regionLngVar2; let countyLatVar2; let countyLngVar2; let countyNameVar; let lngDifference; let countyAbs; let regionLatArray = []; let regionLngArray = []; for (let x in data) { // 先获取值,再处理 regionNameVar2 = data[x]["RegionName"]; regionLatVar2 = data[x]["RegionLat"]; regionLngVar2 = data[x]["RegionLng"]; countyLatVar2 = data[x]["CountyLat"]; countyLngVar2 = data[x]["CountyLng"]; countyNameVar = data[x]["CountyName"]; // 先计算绝对值,再求差值 const regionLngAbs = Math.abs(regionLngVar2); const regionLatAbs = Math.abs(regionLatVar2); countyAbs = Math.abs(countyLngVar2); lngDifference = regionLngAbs - countyAbs; // 可以在这里使用chooseColor const color = chooseColor(lngDifference); // 存入数组 regionLatArray.push(regionLatAbs); regionLngArray.push(regionLngAbs); } }) .catch(function(error) { console.error("加载失败:", error); fetch("./data/trueData.json") .then(res => res.text()) .then(text => console.log("返回内容:", text)); });
内容的提问来源于stack exchange,提问作者Toyu_Frey
相关产品推荐
相关产品推荐

