我正在尝试利用Google SpreadSheets(Google Script)中的地图功能,使用API从Bittrex获取我的帐户硬币余额。这是我的JSON对象:
({success:true,
message:"",
result:[
{Currency:"BTC",
Balance:0.01,
Available:0.01,
Pending:0,
CryptoAddress:null},
{Currency:"ETH",
Balance:1.0,
Available:1.0,
Pending:0,
CryptoAddress:null}
]}
})
理想情况下,我想根据结果中的键和使用每个对象的数据的基础行自动填充标题行。 我看到spme解决方案如何使用每种或更复杂的方式。但我想这可以通过映射来完成。这是我如何映射顶行,但不知道如何映射值:
var headerRow = Object.keys(json.result[0]);
Google SpreadSheet中的预期输出
____________________________________________________________
| Currency | Balance | Available | Pending | CryptoAddress |
|__________________________________________________________|
| BTC | 0.01 | 0.01 | 0 | null |
| ETH | 1.0 | 1.0 | 0 | null |
____________________________________________________________
答案 0 :(得分:1)
我会做以下事情。所以你有了密钥,然后你可以检索它。
Object.keys(json.result[0]).map((val) => { console.log(json.result[0][val])})
在foreach中包装,为每个结果做同样的事情。
希望有所帮助
答案 1 :(得分:0)
以下是完整的工作示例:
function getBalances() {
//Spreadsheet where you store your API key and secret
var keys = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Keys");
// Output empty sheet where balances will be written to
var ex = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Exchanges");
var nonce = 1995932972127042 + new Date().getTime();
var key = keys.getRange("B2").getValue();
var secret = keys.getRange("C2").getValue();
var baseUrl = 'https://bittrex.com/api/v1.1/';
var command = "account/getbalances";
var uri = baseUrl + command + "?apikey=" + key + "&nonce=" + nonce;
var signature = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512,uri,secret);
signature = signature.map(function(byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('')
var headers = {
"apisign": signature
}
var params = {
"method": "GET",
"headers": headers,
}
var response = UrlFetchApp.fetch(uri, params);
var json = JSON.parse(response.getContentText()).result;
var balances = json.map(function(coin) {
return ["Bittrex",coin["Currency"],coin["Balance"]];
}).filter(function(coin) { if (coin[2] !== 0) return coin; });
var headings = ["Exchange","Currency","Balance"];
balances.unshift(headings);
ex.getRange(1, 1, balances.length, balances[0].length).setValues(balances);
}
答案 2 :(得分:0)
似乎你有一个解决方案,但这是另一种方式。
var row = 1;
json.forEach(function(element,index){
row = ++row;
Object.keys(json[index]).forEach(function(e,i)
{
++i;
if(index == 0) {
ex.getRange(1, i).setValue(e);
}
ex.getRange(row , i).setValue(element[e]);
});
});