rahulserver
rahulserver

Reputation: 11205

Dynamically add key val pairs to google app script json

Here is a simple piece of javascript in google app script:

function doGet(e) {
  var outputJSON={};
  outputJSON['k']="m";
  return ContentService.createTextOutput(JSON.stringify(outputJSON))
  .setMimeType(ContentService.MimeType.JSON);
}

This script when run gives the following error:

TypeError: Cannot find function setMimeType in object {"k":"m"}.

This is a perfectly valid javascript. But yet the error occurs, likely due to .setMimeType(ContentService.MimeType.JSON) as when I remove it, the code works. So how to serve such dyamically created jsons from google script?

Upvotes: 0

Views: 984

Answers (1)

Alan Wells
Alan Wells

Reputation: 31300

This seems to work:

function doGet(){
  var outputJSON={};
  outputJSON['k']="m";
  var myJSON_toServe = ContentService.createTextOutput(JSON.stringify(outputJSON));
  myJSON_toServe.setMimeType(ContentService.MimeType.JSON);
  return myJSON_toServe;  
}

It seems like it doesn't like returning the content and chaining methods at the same time.

Upvotes: 2

Related Questions