Google Apps脚本-将UrlFetch响应转换为数组 [英] Google Apps Script - convert UrlFetch response to array

查看:50
本文介绍了Google Apps脚本-将UrlFetch响应转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用UrlFetch从Googe脚本中获取数据:

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

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

正在记录:

[["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?

推荐答案

这取决于查询返回的内容类型.例如,假设它为JSON:

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

   }

这篇关于Google Apps脚本-将UrlFetch响应转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆