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

嵌套JSON数据导入Google Sheets问题求助(含GAS代码)

解决嵌套JSON导入Google Sheets的两个问题

问题1:仅能获取第一个Point数据

你的原代码仅提取了TimeSeries[0].Period[0].Point,只覆盖了第一层单个Point数组。要收集所有Point数据,必须逐层遍历所有嵌套层级:

  • 遍历result中的每个对象
  • 遍历MyEnergyData_MarketDocument.TimeSeries的每个元素
  • 遍历每个TimeSeries下的Period数组元素
  • 遍历每个Period下的所有Point数组(注意:你给出的JSON示例存在重复Point键,这是标准JSON不允许的,解析时后定义的Point会覆盖前一个,需确认原始数据结构是否为Point是二维数组,或Period内包含多个带Point键的对象)

修正后的代码会完整遍历所有嵌套结构,收集所有Point的position和quantity:

var meterdatajson = Utilities.jsonParse(meterdata);
var arrayProperties = [];

// 逐层遍历所有嵌套层级
meterdatajson.result.forEach(function(resultItem) {
  var doc = resultItem.MyEnergyData_MarketDocument;
  doc.TimeSeries.forEach(function(timeSeries) {
    timeSeries.Period.forEach(function(period) {
      // 处理Period下的Point数组:如果是单个Point数组直接遍历
      if (Array.isArray(period.Point)) {
        period.Point.forEach(function(point) {
          arrayProperties.push([point.position, Number(point.quantity)]);
        });
      } else {
        // 若Period下存在多个Point相关数组,遍历所有符合条件的属性
        Object.values(period).forEach(function(pointsArray) {
          if (Array.isArray(pointsArray) && pointsArray[0]?.position) {
            pointsArray.forEach(function(point) {
              arrayProperties.push([point.position, Number(point.quantity)]);
            });
          }
        });
      }
    });
  });
});

var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Forbrug");
// 写入整理后的数据,固定2列(position和quantity)
sheet.getRange(1, 1, arrayProperties.length, 2).setValues(arrayProperties);
// 可选:设置第二列为数值格式,确保显示精度
sheet.getRange(1, 2, arrayProperties.length).setNumberFormat("0.000");

问题2:quantity被自动转为日期格式

这是因为Google Sheets会将类似0.489的字符串误判为日期(0.489天≈11.7小时,会被转成1900年1月1日的对应时间)。解决方法:

  • 将quantity字符串转换为数字类型(代码中用Number(point.quantity)实现),写入时会被识别为数值而非日期
  • 可选:通过setNumberFormat设置列的数值格式,保证显示精度符合需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:45:41