【问题标题】:How to parse JSON in Google Apps Script for Google Spreadsheet如何在 Google 电子表格的 Google Apps 脚本中解析 JSON
【发布时间】:2023-03-05 12:01:01
【问题描述】:

我想从 Bittrex API 中提取数据。我得到了数据,但我无法找到在我的电子表格上显示它们的方法。错误不断出现,这让我很生气!

我确信这真的很简单,但我放弃了:)

代码如下:

function main() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var balancesSheet = ss.getSheetByName("BITTREX 2");
  var balancesRange = balancesSheet.getRange("A1:X");
  var balancesListValues = balancesRange.getValues();

  // Add those values to the active sheet in the current
  // spreadsheet. This overwrites any values that already
  // exist there. 
  balancesSheet.getRange(1, 1, balancesRange.getHeight(), balancesRange.getWidth()) 
    .setValues(balancesListValues);

  var apikey = 'My APY Key is here'; // Please input your key.
  var apisecret = 'My API Secret is here'; // Please input your secret.

  var nonce = Number(new Date().getTime() / 1000).toFixed(0);
  var uri = 'https://bittrex.com/api/v1.1/market/getopenorders?apikey=' + apikey + '&nonce=' + nonce;
  var sign = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, uri, apisecret);
  sign = sign.map(function(e) {return ("0" + (e < 0 ? e + 256 : e).toString(16)).slice(-2);}).join("");
  var params = {
    method: "get",
    headers: {Apisign: sign}
  }

  var response = UrlFetchApp.fetch(uri, params);
  var getContext= response.getContentText();

  var parsedata = JSON.parse(getContext);

  //ss.getRange(1,1).setValue(parsedata.foreach)
  parsedata.data.forEach(function(result, index) {
    balancesListValues.getRange(+3, 1).setValue(result.quantity)
    balancesListValues.getRange(+3, 2).setValue(result.price)
  })
  Logger.log(parsedata.result);
}

这是错误:

TypeError:无法读取未定义的属性“forEach” 在第 31 行(这个:parsedata.data.forEach(function(result, index))

我的目标是在漂亮的电子表格中转换原始 JSON 数据。我愿意接受建议。我做了很多复制/粘贴,所以不要打扰整洁!

感谢您的帮助, NiphtiAe。

编辑

太棒了! 我以该代码结束,以更新数据而不是成排堆积:

 function main() {
      // Retrieve values from API.
      var apikey = '*********'; // Please input your key.
      var apisecret = '**********'; // Please input your secret.
      var nonce = Number(new Date().getTime() / 1000).toFixed(0);
      var uri = 'https://bittrex.com/api/v1.1/account/getbalances?apikey=' + apikey + '&nonce=' + nonce;
      var sign = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, uri, apisecret);
      sign = sign.map(function(e) {return ("0" + (e < 0 ? e + 256 : e).toString(16)).slice(-2);}).join("");
      var params = {
        method: "get",
        headers: {Apisign: sign}

  }
  var response = UrlFetchApp.fetch(uri, params);
  var getContext= response.getContentText();
  var parsedata = JSON.parse(getContext);
  
  console.log(getContext)  // Here, the response value can be confirmed at the log.

  // Use Spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var balancesSheet = ss.getSheetByName("BITTREX 2");
  var balancesRange = balancesSheet.getRange("A1:X");
  var balancesListValues = balancesRange.getValues();
  balancesSheet.getRange(1, 1, balancesRange.getHeight(), balancesRange.getWidth()).setValues(balancesListValues);

  var values = parsedata.result.map(({Currency, Available}) => [Currency, Available]);
  balancesSheet.getRange(1, 1, values.length, values[0].length).setValues(values);
}

只需要从 CMC 或 Coingecko 或其他地方调用价格,瞧!

非常感谢@Tanaike !!

【问题讨论】:

  • 显然 parsedata 不是数组。
  • 请发布您的getContext

标签: javascript json sorting google-apps-script google-sheets


【解决方案1】:

修改点:

  • 从您的TypeError: Cannot read property 'forEach' of undefined on line 31 (this one: parsedata.data.forEach(function(result, index)) 错误消息来看,在这种情况下,我认为parsedata.data 可能会返回null。因为当data的属性作为数组以外的值存在时,就会出现TypeError: parsedata.data.forEach is not a function这样的错误。
    • 看到“GET /market/getopenorders”的官方文档,QuantityPrice的值都包含在result的数组中。 Ref 我认为这可能是您的问题的原因。
  • 而且,QuantityPrice 的键似乎不是 quantityprice
  • 当我看到你的脚本时,似乎balancesListValues 是从var balancesListValues = balancesRange.getValues() 检索到的二维数组。所以当balancesListValues.getRange(+3, 1).setValue(result.quantity)运行时,就会出现错误。
  • 在您的脚本中,setValue 在循环中使用。在这种情况下,工艺成本会变高。

当以上几点反映到你的脚本中时,它变成如下。

修改脚本:

function main() {
  // Retrieve values from API.
  var apikey = 'My APY Key is here'; // Please input your key.
  var apisecret = 'My API Secret is here'; // Please input your secret.
  var nonce = Number(new Date().getTime() / 1000).toFixed(0);
  var uri = 'https://bittrex.com/api/v1.1/market/getopenorders?apikey=' + apikey + '&nonce=' + nonce;
  var sign = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, uri, apisecret);
  sign = sign.map(function(e) {return ("0" + (e < 0 ? e + 256 : e).toString(16)).slice(-2);}).join("");
  var params = {
    method: "get",
    headers: {Apisign: sign}
  }
  var response = UrlFetchApp.fetch(uri, params);
  var getContext= response.getContentText();
  var parsedata = JSON.parse(getContext);
  
  console.log(getContext)  // Here, the response value can be confirmed at the log.

  // Use Spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var balancesSheet = ss.getSheetByName("BITTREX 2");
  var balancesRange = balancesSheet.getRange("A1:X");
  var balancesListValues = balancesRange.getValues();
  balancesSheet.getRange(1, 1, balancesRange.getHeight(), balancesRange.getWidth()).setValues(balancesListValues);

  var values = parsedata.result.map(({Quantity, Price}) => [Quantity, Price]);
  balancesSheet.getRange(balancesSheet.getLastRow() + 1, 1, values.length, values[0].length).setValues(values);
}
  • 在这个修改后的脚本中,检索到的值被放在“BITTREX 2”工作表的第一个空行中。当您想将值放到其他范围时,请修改上面的脚本。

注意:

  • 如果上述修改后的脚本不是您期望的结果,您能否提供console.log(getContext) 的示例值?通过这个,我想检查一下。

参考:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多