我正在尝试解析Google脚本中JSON数组的输出并将其打印到工作表中。工作表中的预期输出:
我当前正在使用以下脚本,该脚本的输出为
有人可以帮我解决我在这里遗失的东西吗?
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)
}
答案 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)
}