我正在尝试使用sendgrid API发送电子邮件。我希望消息的正文包含一个格式化为HTML的json对象。
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": ["GML", "XML"]
},
"GlossSee": "markup"
}
}
}
}
}
但电子邮件的正文看起来是这样的:
{"术语表":{"标题":"示例词汇表";,"GlossDiv":{"标题":"S";,"GlossList":{"GlossEntry":{"ID":"SGML";,"排序方式":"SGML";,"GlossTerm":"标准通用标记语言";,"缩写":"SGML";,"Abbrev":"ISO 8879:1986";,"GlossDef":{"段落":"一种元标记语言,用于创建标记语言,如DocBook&";,"GlossSeeAlso":["GML"、"XML"},"GlossSee":"标记";}}}}}
当我字符串化一个json对象并使用sendgrid API作为HTML发送时,电子邮件正文只是一个很长的文本字符串,很难阅读:(我也尝试过NPM包retty-print-json
所有这些都产生了相同的结果:电子邮件正文只是一个长文本字符串
字符串
let html = stringify.JSON(getStats);
const msg = {
to: 'foo@foo.com',
from: 'foo@foo.com',
subject: datasetTitle,
html: html
}
prettyPrintJson
let html = prettyPrintJson.toHtml(getStats);
const msg = {
to: 'foo@foo.com',
from: 'foo@foo.com',
subject: datasetTitle,
html: html
}
空白,包括换行符,默认情况下在HTML中折叠。将漂亮打印的JSON封装在<pre></pre>
中,输出应该会正确显示。您不需要一个包来添加换行符,只需在序列化JSON.stringify(obj, undefined, 4)
时指定额外的参数即可