简体   繁体   中英

Google Apps Script - convert UrlFetch response to array

I'm using UrlFetch to get data from a Googe script:

var response = UrlFetchApp.fetch(url); 
Logger.log(response.getContentText());
Logger.log(typeof(response))

This is logging:

[["Name","email","2016-12-31T00:00:00.000Z","Sim",548]]
object

The response looks like an array but it is an object. I need to be able to loop through an array, so how do I convert this data to an array instead?

It depends on what type of content returned by the query. Suppose, for example, it JSON:

    function myFunction() {

        var url = "http://headers.jsontest.com/";
        var response = UrlFetchApp.fetch(url); 

        Logger.log(response.getContentText());

        try {
            // Regular expression for JSON content-type
            var jsr = new RegExp(/application\/json/);
            var cnt = response.getAllHeaders()["Content-Type"];

            // Check if response is JSON
            if (jsr.exec(cnt)) {
                // Parse response content
                var js =  JSON.parse( response.getContentText() );
                Logger.log(js);
                for (var i in js) {
                  var t = {}; t[i] = js[i];
                  Logger.log( t );
                }
            }
        } catch(e) {
           Logger.log(e)
        }

   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM