JSON data island

February 12th, 2007. Tagged: JavaScript, JSON

Here's a hacky thing, I called it JSON data island, referencing the XML data island, that MS came up with for their IE browser. The idea is to use a comment in your HTML that holds some data in JSON format. Then using DOM, you access the comment, eval()-uate it and there you go - you have the data as a Javascript object.

» Here's a little proof of concept.

What we have in the HTML is:

<div id="some-div"><!--
    {prop:'value', prop2:['value1','value2','value3']}
-->
    Some stuff in div
</div>

Then the JavaScript that will process the JSON data in the comment:

var island = document.getElementById('some-div').firstChild;
var the_data = eval('(' + island.data + ')');
alert(the_data.prop2);

In this case I added the comment island as the firstChild of some div, but it could be anywhere, as long as you know how to access it with DOM methods.

Q&A

OK, why?
Well, I need some data that comes from the database, so it needs some server-side processing before it appears in the JavaScript code.

Can't it simply be in an inline <script>?
Inline scripts are bad, they mix behaviour (JS) with content (HTML). Also, imagine how your client runs some SEO tool that reports inline scripts in the content, the client goes: "You used an inline script!? Gimme my money back this instant!"

In your external .js then?
I'd like to have external .js simple, with no server-side scripting involved. I don't want to make my beautiful, big, long script appear as something like script.js.php

One small additional little .js.php only for the data you need?
Look, I said "no"! .js.php will require a new database connection, since it's a seperate request. Performance will suffer. In addition it's a new HTTP request and those are expensive.

An AJAX request fired from your beloved clean external .js that will only return the JSON data you hacked into your island thing of yours?
Same as above. New HTTP request, new DB connection.

OK then, I give up!
It was about time!

Thanks: to Phil Renaud for the inspirational idea of making conversational posts, his are hysterical.

Tell your friends about this post: Facebook, Twitter, Google+

10 Responses

  1. I’ve tried integrating something like this into a form validation script (all of the validation regular expressions were placed as comments beside the associated form control) but… and there’s always a “but”; standards purists will point out that the spec states that “Information that appears between comments has no special meaning”. This means our crafty use of comments invalidates the page they are used within. OK, the page still passes the on-line validator but, in purist reality, it fails validation on this point.

    Also, Internet Explorer 5 & 5.5 don’t add comment nodes to the DOM so the script will fail in those browser versions.

    Personally, I like the idea but prefer to get my server-side code to add the appropriate javascript to the head of the document (when possible).

  2. >> Inline scripts are bad, they mix behaviour (JS) with content (HTML).

    Not exactly in this case. It would contain only content, as well as HTML.

  3. [...] JSON data island The idea is to use a comment in your HTML that holds some data in JSON format. Then using DOM, you access the comment, eval()-uate it and there you go – you have the data as a Javascript object. (tags: JSON) [...]

  4. Why not

    And then

    var the_data = eval(‘(‘ + document.getElementById(‘json_data_island’).value + ‘)’);
    alert(the_data.prop2);

    No problems with ie5/5.5, gecko white spaces etc.

  5. blog software had a bug, what i mean was:

    input type=”hidden” id=”json_data_island” value=”{prop:’value’, prop2:['value1','value2','value3']}”

  6. I am a bit confused about json. why to use it? I google it and found that it make easy to interchange information and can be used over xml … well structured , but if I dont use it then wht happened ? what is it purpose ?

    I have used this function for username availability check :

    function ShowAvailability() {
    $.ajax({
    type: “POST”,
    url: “CS.aspx/CheckUserName”,
    data: ‘{userName: “‘ + $(“#”)[0].value + ‘” }’,
    contentType: “application/json; charset=utf-8″,
    dataType: “json”,
    success: OnSuccess,
    failure: function(response) {
    alert(response);
    }
    });
    }

    what if I removed dataType: “json” from this $.ajax method . then what happened?

    I have read article in which its written that :

    You see, in an Ajax environment where we make calls to web services we expect to get some data back in some form. Well, if we receive XML back as a direct result of an Ajax call, we have to send that data through an XML parser before we can even begin to manipulate the data to be useful to JavaScript. If we receive the data in JSON…we don’t have to do anything but assign the results to a variable because JSON is already JavaScript. From there, we can manipulate the data as normal.

    can u provide me example by providing simple code which will illustrate above statement ?

  7. GREAT article. In the land of MVC, REST and AJAX, this is a great solution to handling data that needs to be late-loaded – especially when jQuery is involved. Thanks for sharing.

  8. Hello there, I found your web site via Google even as looking for a comparable matter, your site got here up, it appears to be like good. I’ve bookmarked it in my google bookmarks.

  9. We are a group of volunteers and opening a brand new scheme in our community. Your website provided us with helpful info to paintings on. You have performed a formidable process and our whole group might be grateful to you.

  10. Thanks , I have just been looking for information about this subject for a long time and yours is the greatest I’ve discovered till now. However, what about the conclusion? Are you positive concerning the supply?|What i don’t understood is in reality how you’re now not actually much more smartly-appreciated than you may be right now. You’re so intelligent.

Leave a Reply