Skip to content Skip to sidebar Skip to footer

Map JSON Objects Array To Strings

I'm trying to utilize map function in Google SpreadSheets (Google Script) to get my account coin balances from Bittrex using API. Here is my JSON object: ({success:true, message:

Solution 1:

I would do the following. So you have the key and then you can retrieve the value.

Object.keys(json.result[0]).map((val) => { console.log(json.result[0][val])})

Wrap that within a foreach to do the same for each result.

Hope that helps


Solution 2:

Here is fully working example:

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

Solution 3:

Seems you have a solution, but here is another way.

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]);

  });
});

Post a Comment for "Map JSON Objects Array To Strings"