You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Firebase读取数据至Sheets:getData返回数据的格式适配问题

Solution: Parse Firebase String Arrays into Google Sheets Rows

The core issue here is twofold:

  1. Your Firebase data stores each subTag's value as a string representation of an array (e.g., "["Test1",70,0,18]") instead of a native array.
  2. The data returned from Firebase is an object (with keys like subTag1, subTag2), not a 2D array that Google Sheets' setValues() expects.

Here's how to fix this, with a complete modified function:

function getData() { 
  var ss = SpreadsheetApp.getActiveSpreadsheet(); 
  var sheet = ss.getSheetByName("TestSheet"); 
  var range = sheet.getRange("A1:D2"); 
  var firebaseUrl = "https://.....firebaseio.com/"; 
  var base = FirebaseApp.getDatabaseByUrl(firebaseUrl); 
  var data = base.getData("mainTag"); 

  // Initialize an array to hold rows for Sheets
  var sheetRows = [];

  // Get sorted subTag keys to ensure consistent row order (e.g., subTag1 first)
  var sortedSubTags = Object.keys(data).sort();

  // Process each subTag
  sortedSubTags.forEach(function(subTag) {
    var arrayString = data[subTag];
    try {
      // Parse the string into a native JavaScript array
      var rowData = JSON.parse(arrayString);
      
      // Validate the array has exactly 4 elements (matches your A1:D range)
      if (rowData.length === 4) {
        sheetRows.push(rowData);
      } else {
        Logger.log(`Warning: ${subTag} has ${rowData.length} elements (expected 4)`);
      }
    } catch (error) {
      Logger.log(`Error parsing ${subTag}: ${error.message}`);
    }
  });

  // Write the processed data to Sheets only if we have the correct number of rows
  if (sheetRows.length === 2) {
    range.setValues(sheetRows);
    Logger.log("Successfully wrote data to TestSheet!");
  } else {
    Logger.log(`Expected 2 rows of data, but found ${sheetRows.length}`);
  }
}

Key Steps Explained:

  • Sorting SubTags: Using Object.keys(data).sort() ensures we process subTag1 before subTag2, so your rows end up in the correct order in Sheets.
  • Parsing String Arrays: JSON.parse(arrayString) converts the string representation of the array (e.g., "["Test1",70,0,18]") into a real JavaScript array that Sheets can use directly.
  • Validation: We check that each parsed array has exactly 4 elements to match your A1:D range, preventing errors when writing to Sheets.
  • Error Handling: The try/catch block catches any parsing issues (like malformed array strings) and logs them, so you can debug problematic entries in Firebase.

What If the Values Are Already Native Arrays?

If your Firebase data actually stores native arrays (not strings), the solution simplifies to extracting the object values into a sorted 2D array:

// Replace the processing loop with this:
var sortedSubTags = Object.keys(data).sort();
var sheetRows = sortedSubTags.map(subTag => data[subTag]);

This will work if the log output's ["Test1",70,0,18] represents a real array (not a string).

内容的提问来源于stack exchange,提问作者Stuart Main

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 17:52:55