Google Sheets Apps Script教程JSON解析语法错误求助
Hey there, that error is a super common gotcha when working with APIs in Apps Script—let me break down what's happening and how to fix it.
What's causing the error?
The < token in your error means the response you're trying to parse as JSON is actually HTML content, not valid JSON. This almost always happens when your API request fails (returns a 404, 403, or other error status) and the server sends back an error page instead of the expected JSON data. Your fetchApiResourceObject_ function uses muteHttpExceptions: true, so it doesn't throw an error for bad HTTP statuses—but it still tries to parse the HTML response as JSON, which breaks.
How to debug and fix it
Let's modify your function to add debugging checks so you can see exactly what's going wrong:
function fetchApiResourceObject_(url) { // Make request to API and get response. var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true}); // First, check if the request succeeded var statusCode = response.getResponseCode(); if (statusCode !== 200) { // Log the error details to debug Logger.log(`❌ Request failed with status code: ${statusCode}`); Logger.log(`Response content (first 500 chars): ${response.getContentText().substring(0, 500)}`); throw new Error(`API request failed. Check logs for details. Status code: ${statusCode}`); } // Parse and return the response as a JSON object. var json = response.getContentText(); var responseObject = JSON.parse(json); return responseObject; }
Next steps to troubleshoot
- Run the script and check the logs: Go to
View > Logsin the Apps Script editor. The logs will show you the exact status code and a snippet of the response content. This will tell you if:- The URL is wrong (returns a 404 error page)
- You're missing API credentials or permissions (returns a 403 forbidden page)
- The API endpoint is down or returning unexpected content
- Verify your URL matches the tutorial: Double-check that you copied the API URL correctly—sometimes typos or missing parameters (like API keys) cause these errors.
- Check tutorial prerequisites: Make sure you completed all setup steps in the codelab, like enabling any required APIs or configuring authentication for the request.
Once you see the actual error response in the logs, it'll be much easier to pinpoint and fix the issue!
内容的提问来源于stack exchange,提问作者Starnes Student

