首页 > 解决方案 > JavaScript:如何将 JSON 格式化为 HTML 以发送电子邮件?

问题描述

在我的应用程序中,任何错误都会被捕获并通过电子邮件发送以供审核。我目前正在向电子邮件中添加标题和正文以帮助重现错误。它当前显示在单行中。我想以格式化的方式显示这一行,以便更容易阅读电子邮件。

我目前正在使用JSON.stringify(myJsonHere, null, 2)格式化我的 JSON。如果我console.log(JSON.stringify(myJsonHere, null, 2))用来显示它,它确实有效,但当我将它添加到 HTML 电子邮件(如'<b>Headers:</b> ' JSON.stringify(myJsonHere, null, 2).

我的目标是获得这种格式:

{
  data: "test",
  id: 1,
  user: {
    id: 1,
    user: "test"
  }
}

而不是这种格式:

{data: "test", id: 1, user: {id: 1, user: "test"}}

标签: javascriptjsonformatting

解决方案


const pre = document.querySelector('pre');

pre.innerHTML = JSON.stringify({ test: 1, nested: { a: 1} }, null, 2)
<pre></pre>


推荐阅读