Javascript 是否有在 HTML 中嵌入 JSON 的标准?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14395682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:38:23  来源:igfitidea点击:

Is there a standard for embedding JSON in HTML?

javascripthtmljsoninlinedot.js

提问by TJ.

I would like to embed JSON in HTML. The most elegant solution I have found makes use of the script-tag and the mime media type application/json.

我想在 HTML 中嵌入 JSON。我发现的最优雅的解决方案是使用script-tag 和 mime 媒体类型application/json

<script id="data" type="application/json">
    {
        "foo" : "bar"
    }
</script> 

Is this the standard way of embedding JSON? If not, are there any risks with the above solution?

这是嵌入 JSON 的标准方法吗?如果没有,上述解决方案是否存在任何风险?

Reasons for using inline JSON (instead of a JSON-P service):

使用内联 JSON(而不是 JSON-P 服务)的原因:

  • Small amounts of JSON-data
  • Less HTTP-requests
  • Preference for inline-JSON to data in HTML-attributes
  • 少量 JSON 数据
  • 更少的 HTTP 请求
  • 内联 JSON 优先于 HTML 属性中的数据

[UPDATE]Reason for embedding json.

[更新]嵌入 json 的原因。

I have a gallery widget for a website with very high traffic. The gallery can consist of a 100 images or more. I am only showing one image at a time and the rest of the images will be lazy loaded. However the information (image src) to all images will be rendered in the html on page load. There are various ways to render the image information in the html. Instead of using JSON I could also use html data attributes as shown below:

我有一个用于流量非常高的网站的图库小部件。图库可以包含 100 张或更多图像。我一次只显示一张图片,其余的图片将被延迟加载。但是,所有图像的信息(图像源)将在页面加载时呈现在 html 中。有多种方法可以在 html 中呈现图像信息。除了使用 JSON,我还可以使用 html 数据属性,如下所示:

<li class="image" data-src="image-path.jpg">
    <!-- image tag will be created here using javascript -->
</li>

Will result in:

会导致:

<li class="image image-loaded" data-src="image-path.jpg">
    <img src="image-path.jpg" />
</li>

The disadvantage with the above solution is the extra markup. I would rather use JSON and a Javascript-Templating engine such as doT.js.

上述解决方案的缺点是额外的标记。我宁愿使用 JSON 和 Javascript 模板引擎,例如doT.js

采纳答案by Bergi

Reasons for using inline JSON (instead of a JSON-P service)

使用内联 JSON(而不是 JSON-P 服务)的原因

You can inline JSON-P as well. OK, you just call that method "inline script", but it has the advantages of both :-)

您也可以内联 JSON-P。好的,您只需将该方法称为“内联脚本”,但它具有两者的优点:-)

回答by TJ.

I am answering my own question since I have had to find a solution. My solution is based on what Bergisuggested using inline JSONP. It is a better solution than finding an answer to my actual question since no manual JSON-parsing is required.

我正在回答我自己的问题,因为我必须找到解决方案。我的解决方案基于Bergi建议使用内联 JSONP。这是比为我的实际问题找到答案更好的解决方案,因为不需要手动 JSON 解析。

The JSON-data (and HTML) is generated with Java Server Pages (JSP).

JSON 数据(和 HTML)是使用 Java Server Pages (JSP) 生成的。

Step 1

第1步

A custom variable name is created using JSP. It will be used as the javascript global variable to which the json data will be assigned to. The name is randomly generated to prevent naming conflicts on the same page.

自定义变量名称是使用 JSP 创建的。它将用作 json 数据将分配给的 javascript 全局变量。名字是随机生成的,防止同一个页面的命名冲突。

<c:set var="jsonpVarName">jsnpData<%= java.lang.Math.round(java.lang.Math.random() * 1000000) %></c:set>    

Step 2The script tag has a cssClassname to identify it by and a data-var-attribute, so that the custom variable name can be determined. ${ctrl.json}is JSP and prints out JSON. Unlike JSONP which uses a callback-Function, a global variable is used. So far I have not experienced any drawbacks.

步骤2script标签有一个cssClassname来标识它,还有一个data-var-attribute,这样可以确定自定义变量名。${ctrl.json}是 JSP 并打印出 JSON。与使用回调函数的 JSONP 不同,使用全局变量。到目前为止,我还没有遇到任何缺点。

<script class="data" data-var="${jsonpVarName}" type="text/javascript">
    window.${jsonpVarName} = ${ctrl.json};
</script>

Step 3Accessing the data (using jQuery) is as easy as:

第 3 步访问数据(使用 jQuery)非常简单:

var data = window[$('script.data').data('var')];

Example with context

带上下文的示例

HTML

HTML

<div class="myWidget">
    <button class="fetchData">Fetch Data</button>


    <c:set var="jsonpVarName">jsnpData<%= java.lang.Math.round(java.lang.Math.random() * 1000000) %></c:set>

    <script class="data" data-var="${jsonpVarName}" type="text/javascript">
        window.${jsonpVarName} = ${ctrl.json};
    </script>

</div> 

Javascript

Javascript

$('button.fetchData', '.myWidget').click(function (e) {

    var data = window[$('script.data', '.myWidget').data('var')];    

});

I'm using inline JSONP to load JSON-data which is required on page load. It isn't a lot of data and it's one HTTP-Request less.

我正在使用内联 JSONP 来加载页面加载所需的 JSON 数据。它的数据并不多,而且少了一个 HTTP 请求。

回答by Domi

What you suggest is absolutely correct. The typeattributes of the scripttag must be a valid MIME descriptor. According to the official JSON RFCsection 6 "IANA Considerations":

你的建议是完全正确的。标签的type属性script必须是有效的 MIME 描述符。根据官方 JSON RFC第 6 节“IANA 注意事项”:

The MIME media type for JSON text is application/json.
Type name: application
Subtype name: json

JSON 文本的 MIME 媒体类型是 application/json。
类型名称:应用程序
子类型名称:json

So your HTML is valid:

所以你的 HTML 是有效的:

<script id="data" type="application/json">
    {
        "foo" : "bar"
    }
</script> 

And, no, there are no additional risks involved in doing this.

而且,不,这样做没有额外的风险。

回答by mahmoud

try http://json2html.com/that's a good way to Transform JSON to HTML.

尝试http://json2html.com/这是将 JSON 转换为 HTML 的好方法。