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 on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov