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

向Google Sheets自定义函数传递JSON遇解析错误,求解决方案

问题解决:Google Sheets自定义函数WPLAN公式解析错误及JSON参数处理

核心原因

Google Sheets公式语法不支持直接传入原生JSON对象,也不能直接传递未转义的JSON字符串——公式中字符串用双引号包裹,内部未转义的双引号会导致字符串提前闭合,触发解析错误。

可行解决方案

1. 转义JSON字符串中的双引号

在Sheets公式里,字符串内部的双引号需要用**两个双引号("")**转义,将转义后的JSON字符串作为参数传入,最后在Apps Script中用JSON.parse()解析:

=WPLAN(30, 5, "[{""workoutType"": ""Lower Body"", ""percentage"": 60, ""tagPercentages"": [{""tag"": ""squats"", ""percentage"": 60}, {""tag"": ""lowimpact"", ""percentage"": 40}]}, {""workoutType"": ""Upper Body"", ""percentage"": 40, ""tagPercentages"": [{""tag"": ""pushups"", ""percentage"": 50}, {""tag"": ""weights"", ""percentage"": 50}]}]")

函数内解析示例:

function WPLAN(duration, rounds, jsonStr) {
  const workoutConfig = JSON.parse(jsonStr);
  // 后续业务逻辑处理
}

2. 用单元格引用传递JSON

将标准JSON文本粘贴到某个单元格(比如A1),公式中直接引用该单元格,无需处理转义:

=WPLAN(30, 5, A1)

函数内同样用JSON.parse(jsonStr)解析即可。

3. 用结构化单元格区域作为参数

把训练配置整理成表格区域(更贴合Sheets使用习惯),比如:

训练类型占比标签1标签1占比标签2标签2占比
Lower Body60squats60lowimpact40
Upper Body40pushups50weights50

然后公式引用该区域:

=WPLAN(30, 5, B2:F3)

函数内处理二维数组示例:

function WPLAN(duration, rounds, configRange) {
  const workoutConfigs = configRange.map(row => {
    return {
      workoutType: row[0],
      percentage: row[1],
      tagPercentages: [
        { tag: row[2], percentage: row[3] },
        { tag: row[4], percentage: row[5] }
      ]
    };
  });
  // 后续业务逻辑处理
}

4. 拆分参数为独立输入

如果训练类型数量固定,可将每个训练的配置拆分为独立参数,简化输入:

=WPLAN(30, 5, "Lower Body", 60, "squats:60,lowimpact:40", "Upper Body", 40, "pushups:50,weights:50")

函数内解析示例:

function WPLAN(duration, rounds, ...args) {
  const workoutConfigs = [];
  for (let i = 0; i < args.length; i += 3) {
    const tags = args[i+2].split(',').map(tagStr => {
      const [tag, percentage] = tagStr.split(':');
      return { tag, percentage: parseInt(percentage) };
    });
    workoutConfigs.push({
      workoutType: args[i],
      percentage: parseInt(args[i+1]),
      tagPercentages: tags
    });
  }
  // 后续业务逻辑处理
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 06:55:00