Google Apps Script解析Mopar车辆召回API返回JSONP数据报错求解
Google Apps Script 处理Mopar召回API JSONP响应方案
核心处理逻辑
JSONP格式本质是回调函数包裹JSON字符串,你遇到的报错是因为直接解析包含showVinInfo(前缀和)后缀的非标准JSON字符串导致的,适配所有返回场景的提取方案如下:
完整可运行代码示例
function getMoparRecallByVin(vin) { // 配置API请求参数,替换为你实际使用的接口地址、请求头 const apiUrl = `你的Mopar API接口地址?vin=${vin}`; const options = { method: 'GET', headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36', // 其他接口要求的头信息按需添加 }, muteHttpExceptions: true }; try { const response = UrlFetchApp.fetch(apiUrl, options); const jsonpContent = response.getContentText(); // 通用JSONP内容提取,适配换行、末尾有无分号的所有场景 // 正则说明:s修饰符支持匹配换行内容,兼容接口返回带换行的场景 const jsonMatch = jsonpContent.match(/^showVinInfo\((.*)\);?$/s); if (!jsonMatch || jsonMatch.length < 2) { throw new Error('响应内容不符合JSONP格式预期'); } // 提取纯JSON字符串并解析 const recallData = JSON.parse(jsonMatch[1].trim()); // ========== 以下为Google Sheets字段写入逻辑,按需调整 const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // 目标行号可根据你的表格规则修改 const targetRow = sheet.getLastRow() + 1; // 示例写入字段:VIN、召回总数、召回编号、召回描述、修复状态 sheet.getRange(targetRow, 1).setValue(recallData.vin || vin); sheet.getRange(targetRow, 2).setValue(recallData.recalls ? recallData.recalls.length : 0); if (recallData.recalls && recallData.recalls.length > 0) { recallData.recalls.forEach((recall, index) => { const recallRow = targetRow + index; sheet.getRange(recallRow, 3).setValue(recall.recallNumber || ''); sheet.getRange(recallRow, 4).setValue(recall.description || ''); sheet.getRange(recallRow, 5).setValue(recall.remedyStatus || ''); }); } return recallData; } catch (err) { console.error('处理失败:', err.message); const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); const targetRow = sheet.getLastRow() + 1; sheet.getRange(targetRow, 1).setValue(vin); sheet.getRange(targetRow, 2).setValue('查询失败:' + err.message); } }
关键注意点
- 正则使用
s修饰符匹配换行符,适配接口返回JSON内容带换行的场景,不会出现截断问题 - 异常处理逻辑覆盖网络请求失败、格式不匹配、字段为空的所有边界场景
- 字段映射部分可根据Mopar接口实际返回的字段名调整,你可以先执行
console.log(recallData)打印完整返回结构,确认字段名称后替换示例中的占位字段名即可
内容的提问来源于stack exchange,提问作者FIRELAND CDJR
相关产品推荐
相关产品推荐

