javascript - 在 DOM 中嵌入任意 JSON 的最佳实践?

我正在考虑像这样在 DOM 中嵌入任意 JSON:

<script type="application/json" id="stuff">
    {
        "unicorns": "awesome",
        "abc": [1, 2, 3]
    }
</script>

这类似于将任意 HTML 模板存储在 DOM 中以供以后与 JavaScript 模板引擎一起使用的方式。在这种情况下,我们可以稍后检索 JSON 并解析它:

var stuff = JSON.parse(document.getElementById('stuff').innerHTML);

This works ,但这是最好的方法吗?这是否违反任何最佳实践或标准?

注意:我不是在寻找将 JSON 存储在 DOM 中的替代方法,我已经确定这是解决我遇到的特定问题的最佳解决方案。我只是在寻找最好的方法。

最佳答案

我认为你原来的方法是最好的。 HTML5 规范甚至解决了这种用途:

"When used to include data blocks (as opposed to scripts), the data must be embedded inline, the format of the data must be given using the type attribute, the src attribute must not be specified, and the contents of the script element must conform to the requirements defined for the format used."

在此处阅读:http://dev.w3.org/html5/spec/Overview.html#the-script-element

你确实做到了。什么是不爱?无需对属性数据进行字符编码。您可以根据需要对其进行格式化。它具有表现力,预期用途很明确。感觉不像是 hack(例如,使用 CSS 来隐藏你的“载体”元素)。这是完全有效的。

https://stackoverflow.com/questions/9320427/

相关文章:

python - JSON到 Pandas 数据框

json - 在 JSON 结果中定义函数是否有效?

jquery - 如何检查值是否为 JSON 对象?

javascript - 嵌套的 JSON 对象 - 我必须对所有内容都使用数组吗?

json - 如何使用 jq 合并来自 2 个文件的 2 个 JSON 对象?

javascript - 如何通过 JavaScript for 循环创建 json?

javascript - 将 Javascript 对象编码为 Json 字符串

ruby-on-rails - 将 json 格式的键值对转换为以符号为键的 ruby​​ 哈希的最

c# - 如何从 JSON 字符串自动生成 C# 类文件

javascript - 将json数据转换为html表