最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there a standard for embedding JSON in HTML? - Stack Overflow

programmeradmin1浏览0评论

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.

<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?

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

  • Small amounts of JSON-data
  • Less HTTP-requests
  • Preference for inline-JSON to data in HTML-attributes

[UPDATE] Reason for embedding 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:

<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.

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.

<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?

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

  • Small amounts of JSON-data
  • Less HTTP-requests
  • Preference for inline-JSON to data in HTML-attributes

[UPDATE] Reason for embedding 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:

<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.

Share Improve this question edited Nov 16, 2014 at 1:17 JstnPwll 8,6852 gold badges35 silver badges57 bronze badges asked Jan 18, 2013 at 9:16 T. JunghansT. Junghans 11.7k8 gold badges54 silver badges77 bronze badges 13
  • 2 What are you going to do with the json your are "embedding"? – PeeHaa Commented Jan 18, 2013 at 9:21
  • 2 You're better off storing the json as an object in javascript. There is no reason to have embedded json, unless you're somehow going to avoid using javascript to access that json again. – dead Commented Jan 18, 2013 at 9:24
  • 3 JSON is a method for transferring data. It's not something that should be used for its own sake. Especially when you're dealing with JavaScript, there's practically no reason to prefer JSON (JavaScript Object Notation) over actual JavaScript objects. – JJJ Commented Jan 18, 2013 at 9:29
  • Is it static content you want to embed? Or would you serve the HTML files prepopulated with the embedded JSON? Otherwise I don't see any advantage to embed the JSON directly in HTML – intuitivepixel Commented Jan 18, 2013 at 9:30
  • @PeeHaa: I have updated my question with a reason. – T. Junghans Commented Jan 18, 2013 at 9:36
 |  Show 8 more comments

4 Answers 4

Reset to default 8

What you suggest is absolutely correct. The type attributes of the script tag must be a valid MIME descriptor. According to the official JSON RFC section 6 "IANA Considerations":

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

So your HTML is valid:

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

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

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

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

Step 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.

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

Step 2 The 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.

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

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

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

Example with context

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

$('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.

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

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

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

发布评论

评论列表(0)

  1. 暂无评论