Search code examples
jsongoogle-apps-scriptjsonp

Consuming JSONP in Google Apps Script


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);
}

Solution

  • 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());