Javascript中JSON.parse解析合法JSON字符串报错问题求助
问题根因排查
报错核心问题出在JSON切片逻辑上:resp.indexOf(']') 只会匹配字符串中第一个出现的]字符,你提供的JSON结构里,services内嵌数组结束的位置就存在第一个],你的切片逻辑直接在这里截断了字符串,导致最终传给JSON.parse()的内容是不完整的JSON结构,自然会抛出Unexpected end of JSON input的报错。
你之前手动复制完整JSON到校验工具能通过,是因为你用的是完整内容,而代码实际运行时切出来的字符串是残缺的。
修复方案
把切片的结束位置从匹配第一个]改成匹配最后一个]即可,修改后的代码如下:
var url = 'http://localhost/helpinghands/public/index.php/services/getUsers';//Gets all users, complete with services offered and the appropriate marker color var request = new XMLHttpRequest(); request.open('GET',url); request.onload = function(){ if(request.status === 200){ var resp = request.responseText; // 把indexOf改为lastIndexOf,匹配外层数组的结束 ] 位置 var slice = resp.slice(resp.indexOf('['),resp.lastIndexOf(']')+1); var data = JSON.parse(slice); //var userLat = Number(data[0].lat); alert(data); //var userLong = Number(data.lng); //const loc = new point(userLat,userLong);//This is the location from the database for that user //create marker object for loc by passing Marker constructor references to the loc and map objects, which are assigned to position and map variables, respectively //const marker = new google.maps.Marker({map: map,position: loc, title: data.name}); } };
验证建议
如果担心还有其他特殊字符影响解析,可以在切片后加调试日志,确认切出的内容是否符合预期:
console.log('实际切片内容:', slice);
内容的提问来源于stack exchange,提问作者naturevet
相关产品推荐
相关产品推荐

