Consuming JSONP in Google Apps Script

2019-09-09 23:05发布

问题:

I'd like to consume the following URL in my Google Apps Script: http://a0.awsstatic.com/pricing/1/emr/pricing-mapr.min.js

Using the typical response = UrlFetchApp.fetch(url).getContentText() doesn't really work, it just returns the JSON surrounded by callback(). Is there a way to consume JSONP with Google Apps Script?

Code:

function myFunction() {
  getEmrPricingData_();

}

/*
 * Get EMR Prices
 *
 */
function getEmrPricingData_() {
  var emr_url = "http://a0.awsstatic.com/pricing/1/emr/pricing-mapr.min.js"
  var response = UrlFetchApp.fetch(emr_url).getContentText();
  Logger.log(response);
}

回答1:

You need to define the function callback() in your code, and eval() your JSONP response to execute that function. For example to handle JSONP responses on a project of mine I created this function:

function callback(data){
    return data;
}

and in my request function:

var result = eval(UrlFetchApp.fetch(url + uri, options).getContentText());