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

如何在SendGrid模板中序列化未知结构的JSON对象?

在SendGrid模板中序列化未知结构的对象

可以实现,SendGrid的模板基于Handlebars语法,默认直接输出对象会显示[object Object],你需要自定义一个Handlebars助手函数来实现JSON序列化,具体步骤如下:

  • 步骤1:在发送邮件的代码中注册自定义助手
    以Node.js环境为例,使用SendGrid SDK时,你可以在配置邮件模板时添加一个json助手,实现JSON.stringify的功能:

    const sgMail = require('@sendgrid/mail');
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    
    // 注册自定义Handlebars助手
    sgMail.setSubstitutionWrappers('{{', '}}');
    sgMail.addHelper('json', function(context) {
      return JSON.stringify(context);
    });
    
    // 构造邮件数据
    const msg = {
      to: 'recipient@example.com',
      from: 'sender@example.com',
      templateId: 'your-template-id',
      dynamicTemplateData: {
        test: {"foo": { "bar": {"foo2": "bar2"}}}
      }
    };
    
    sgMail.send(msg);
    
  • 步骤2:在SendGrid模板中使用该助手
    修改你的模板代码,调用自定义的json助手来序列化对象:

    ... what is inside the test object: {{json test}}
    

    如果需要避免HTML转义(比如保留JSON的引号和大括号格式),可以使用三个大括号:

    ... what is inside the test object: {{{json test}}}
    

这样就能得到你期望的JSON字符串输出了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 04:01:55