Search code examples
jsongoogle-apps-scriptloggingstringify

JSON.stringify print all objects in an array as [{},{},{}]


When I run this code, I get the following output:

var triggers = ScriptApp.getProjectTriggers();
Logger.log("triggers =" + JSON.stringify(triggers));
for (var j = 0; j < triggers.length; j++) {
  Logger.log("trigger +"[i]+" =" + JSON.stringify(triggers[i]));
}
};

Output:

5:55:16 PM  Info    triggers =[{}, {}, {}]
5:55:16 PM  Info    t ={}

I know there are a few not empty objects, why aren't they shown as a string?


Solution

  • The return value from ScriptApp.getProjectTriggers() is an array of Trigger objects - and these objects do not appear to have a toJSON method or values which can be stringified.

    See this question Why does JSON.stringify return empty object notation “{}” for an object that seems to have properties? for more background.

    I assume you have an array of three trigger objects, judging by your output [{}, {}, {}].

    You can iterate over your array to access its properties - for example, as follows:

    var triggers = ScriptApp.getProjectTriggers();
    for (var i = 0; i < triggers.length; i++) {
      Logger.log( triggers[i].getEventType() );
    }
    

    Assuming you have 1 time-based trigger and 1 calendar event trigger attached to your script, you will see the following output:

    3:54:07 PM  Info    CLOCK
    3:54:07 PM  Info    ON_EVENT_UPDATED
    

    A more compact way to iterate is:

    var triggers = ScriptApp.getProjectTriggers();
    triggers.forEach(trigger => Logger.log( trigger.getEventType() ));
    

    See the documentation here for more details on what properties you can access for each trigger.