使用JavaScript或jQuery遍历JSON API遇语法错误求解决
解决JSON API遍历的语法错误与遍历方法
兄弟,我来帮你搞定这个问题!你遇到的Uncaught SyntaxError: Unexpected token :错误其实挺常见的,先给你拆解下可能的原因,再给你JavaScript和jQuery两种靠谱的遍历方案:
一、先搞懂报错的根源
这个错误90%是以下两种情况:
- 拿到的响应不是合法JSON:比如服务器返回的是JSONP格式(带回调函数包裹,比如
callback({...})),或者返回了HTML错误页(比如404、500页面),导致浏览器解析JSON时失败 - JSON本身有语法问题:你贴的示例末尾是
stat...,可能实际返回的JSON没闭合、有多余逗号或者引号不配对,这种情况得先确认API返回的内容是否合法
二、jQuery遍历方案(简单省心)
用jQuery的$.getJSON()是最省心的,它会自动帮你处理JSON解析,不用手动折腾:
// 替换成你的API地址 $.getJSON('https://your-api-url.com/matches', function(response) { // 先判断API返回的success状态 if (response.success) { // 遍历data里的match数组 response.data.match.forEach(function(match) { console.log('比赛ID:', match.id); console.log('对阵双方:', match.home_name + ' VS ' + match.away_name); console.log('当前比分:', match.score); console.log('比赛时长:', match.time + '分钟'); // 其他字段比如ht_score、league_id都可以这么取 }); } else { console.log('API请求失败:', response.message || '未知错误'); } }) // 捕获请求或解析错误 .fail(function(jqXHR, textStatus, errorThrown) { console.error('出错啦:', textStatus, errorThrown); // 这里可以打印原始响应,看看是不是合法JSON console.log('原始响应内容:', jqXHR.responseText); });
三、原生JavaScript遍历方案(无依赖)
如果不想用jQuery,原生fetchAPI也能搞定:
// 替换成你的API地址 fetch('https://your-api-url.com/matches') .then(response => { // 先检查HTTP请求是否成功 if (!response.ok) { throw new Error(`请求失败!状态码: ${response.status}`); } // 解析JSON,不合法的话会抛出错误 return response.json(); }) .then(result => { if (result.success) { // 用for...of遍历match数组 for (const match of result.data.match) { console.log(`【比赛${match.id}】${match.home_name} ${match.score} ${match.away_name},已进行${match.time}分钟`); // 按需处理其他字段 } } else { console.log('API返回失败:', result.message); } }) .catch(error => { console.error('请求或解析出错:', error); // 如果是解析错误,打印原始响应确认问题 fetch('https://your-api-url.com/matches') .then(res => res.text()) .then(rawContent => console.log('原始响应:', rawContent)); });
四、如果是JSONP格式的特殊情况
如果你的API返回的是JSONP(比如响应是callback({"success": true, ...})这种带回调包裹的格式),那得用jQuery的$.ajax指定dataType: 'jsonp':
$.ajax({ url: 'https://your-api-url.com/matches', dataType: 'jsonp', jsonpCallback: 'callback', // 要和API返回的回调函数名一致,留空的话jQuery会自动生成 success: function(response) { if (response.success) { // 同样遍历match数组 response.data.match.forEach(match => { // 处理逻辑 }); } } });
最后排查小技巧
打开浏览器的开发者工具→网络面板,找到这个API请求,查看「响应」标签页:
- 如果是带回调的JSONP,就用上面的JSONP方案
- 如果是HTML页面,说明API地址错了或者服务器挂了
- 如果JSON有语法高亮错误,那就是API本身的问题,得联系提供者修复
内容的提问来源于stack exchange,提问作者meangrizzle
相关产品推荐
相关产品推荐

