使用Google脚本解析Json数组

时间:2018-10-31 05:26:41

标签: arrays json google-apps-script

我正在尝试解析此JSON数组,但我不熟悉如何在Google脚本中循环遍历JSON。我在此API中收到价格变量的未定义错误。

API link

 function CBAPI() {

      // Link the script with a spreadsheet using the unique identifier found in the spreadsheet web address
      var ss = SpreadsheetApp.openById('16UqqC_MjnRfwbpREUcrcl7q69bUjzPgoUm6ZBMorizk');

      var APIPullSheet = ss.getSheetByName("APIPull");

      // Clear Columns A, B, C & D
      APIPullSheet.getRange('A2:F19999').clearContent();

      var url= "https://api.coinmarketcap.com/v2/ticker/132";
      var responseAPI = UrlFetchApp.fetch(url);
      var parcedData = JSON.parse(responseAPI.getContentText());


      var id = [];
      var price = [];


          id.push(['id']);
          price.push(['price']);

      id.push([parcedData.data.id]);
      price.push([parcedData.data.price]);



      idRange = APIPullSheet.getRange(1, 1, id.length, 1);  // Put isFrozen in column A
      idRange.setValues(id);

      priceRange = APIPullSheet.getRange(1, 2, price.length, 1);  // Put lowestAsk in column B
      priceRange.setValues(price);


      // Append Latest Data to End of the File
      var tableData = ss.getSheetByName("TableData");
      var rangeData = tableData.getRange("H1:K1");  
      var latestData = rangeData.getValues();   // Put I1 to O1 in latestData variable
      tableData.appendRow(latestData[0]);   // Put the data at the bottom of the spreadsheet

      // Keep 144 rows - Delete any extra starting at row 2
      var rowsToKeep = 5000;   // 5000 at request of Edwin
      var totalRows = tableData.getLastRow();
      var numToDelete = totalRows - rowsToKeep;
        if (numToDelete > 0)
           {
             tableData.deleteRows(2, numToDelete);  // Purge Extra Rows - Starting With Row 2 (oldest)
           }

    }

1 个答案:

答案 0 :(得分:0)

API返回报价对象内的价格。

替换:

  price.push([parcedData.data.price]);

使用:

  price.push([parcedData.data.quotes.USD.price]);

enter image description here