将JSON数组输出打印到Google表格

时间:2020-02-08 15:18:47

标签: arrays json google-apps-script google-sheets jsonparser

我正在尝试解析Google脚本中JSON数组的输出并将其打印到工作表中。工作表中的预期输出:

  • 第1行:AUD |人民币|英镑|港币
  • 行2:0.98 | 5.01 | 0.56 | 5.60
  • 行3:0.91 | 8.01 | 0.93 | 2.61

我当前正在使用以下脚本,该脚本的输出为

  • 第1行:{AUD = 0.98,HKD = 5.01,GBP = 0.56,CNY = 5.60}
  • 第2行:{AUD = 0.91,HKD = 8.01,GBP = 0.93,CNY = 2.61}

有人可以帮我解决我在这里遗失的东西吗?

    function addObject(){
     var obj = {
        "base": "CAD",
        "date": "2017-05-05",
        "rates": [{
            "AUD": "0.98",
            "CNY": "5.01",
            "GBP": "0.56",
            "HKD": "5.60"
        },
                 {
            "AUD": "0.91",
            "CNY": "8.01",
            "GBP": "0.93",
            "HKD": "2.61"
        }]
    }
    var inputArray = []
    var rates = obj.rates
    for (var j in rates){
      inputArray.push([rates[j]])
    }
    Logger.log(inputArray)
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName('Sheet1');
    sheet.getRange(sheet.getLastRow()+1, 1,inputArray.length,inputArray[0].length).setValues(inputArray)

    }

2 个答案:

答案 0 :(得分:3)

您需要将数组转换为二维数组:

let obj = {
    "base": "CAD",
    "date": "2017-05-05",
    "rates": [{
        "AUD": "0.98",
        "CNY": "5.01",
        "GBP": "0.56",
        "HKD": "5.60"
    },
             {
        "AUD": "0.91",
        "CNY": "8.01",
        "GBP": "0.93",
        "HKD": "2.61"
    }]
}

let headers = Object.keys(obj.rates[0]);
let out = obj.rates.map(({AUD,CNY,GBP,HKD})=> [AUD,CNY,GBP,HKD]);
out.unshift(headers);
console.log(out);//setvalues this array: out

答案 1 :(得分:2)

上一个:V8

function doit() {
  var obj = {
    "base": "CAD",
    "date": "2017-05-05",
    "rates": [{
      "AUD": "0.98",
      "CNY": "5.01",
      "GBP": "0.56",
      "HKD": "5.60"
    },
              {
                "AUD": "0.91",
                "CNY": "8.01",
                "GBP": "0.93",
                "HKD": "2.61"
              }]
  }

  var headers=Object.keys(obj.rates[0]);
  var out=obj.rates.map(function({AUD:AUD,CNY:CNY,GBP:GBP,HKD:HKD}){ return [AUD,CNY,GBP,HKD]});
  out.unshift(headers);
  //Logger.log(out);
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet1');
  //sh.clearContents();
  sh.getRange(sh.getLastRow()+1,1,out.length,out[0].length).setValues(out)
}