Wednesday, October 08, 2008

HTML encapsulated JSON

Continuing the early morning post on having an XSL-like solution for JSON, where your webapp only outputs JSON files, and has attached stylesheet(s) that the browsers can use to display it as a nicely formatted HTML it intended for human audience. All solutions I outlined there needed an active change to existing technologies: custom HTTP header, or extension to JSON, but in any case they would need explicit support from browsers. 


In other words, they would never get widely adopted. 

But then, just as I went to sleep, it hit me that there's a solution that operates completely within the currently existing technologies. I'll call this solution "HTML encapsulated JSON". The premise is that you create a simple HTML page that has the JSON payload in its body, and has script elements that pull in the JSON-to-DOM transforming script. Something like this:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="/carlist-json-to-html.js" type="text/javascript" />
<link rel="stylesheet" type="text/css" href="carlist.css" />
</head>
<body>
<pre>
{ "cars": [
{ "color": "red",
"make": "Ford",
"model": "Mustang",
"year": 1986,
"price": {
"amount": 250,
"currency": "USD"
}
},
{ "color": "yellow",
"make": "Mazda",
"model": "6",
"type": "GT",
"year": 2002,
"price": {
"amount": 14000,
"currency": "USD"
}
}
],
"dealer": {
"name": "Honest Joe",
"address": {
"street": "123 7th Avenue",
"city": "Dustfield"
},
"phone": "1-456-789789"
}
}
</pre>
</body>
</html>

As you can see, the JSON is put into html/body/pre (using "pre" to be fully DTD conformant). A machine client should be able to easily parse it out from there. Granted, it'll need to use both an XML parser and then a JSON parser, but that shouldn't be too big deal.
But the best part is definitely that you can very easily transform this into a nicely formatted HTML, by including a script (emphasized in red) to build a DOM from the JSON extracted from the body. Actually, you can just generate a fairly naked HTML, and then use a separate CSS stylesheet (as shown above) to format the HTML for presentation! And it's all standards compliant, and works with any modern browser!
Next, I'll try to come up with typical code for a JavaScript code template that would be used for a JSON-to-DOM conversion.

1 comment:

cutiesxxbaby said...

hi then how can i use it with ajax and retrieve only two eg color and model