Projects by
Thomas Greiner
greinr.com blog
web log
Proof-of-Concept Projects
subscribe
follow
flattr

JSONS - JSON in a Stylesheet

The idea behind JSONS is similar to JSONP in regard to it being used to transfer JSON data across different domains by wrapping it inside another layer.

The main difference is that JSONP is transmitted as JavaScript while JSONS is transmitted as CSS. Naturally, JSONP is better in many aspects such as performance and ease-of-use but the main advantage of JSONS is that it avoids any third-party code execution.

How JSONP works

JSONP executes JavaScript from a potentially third-party domain on the webpage and calls a callback function to which it passes the JSON object. However, this raises security concerns because it can execute any kind of JavaScript code on that page.

JSONP Request URL
http://example.com/api?callback=<callback>

JSONP Response Content
<callback>(<json>)

Usage (Client)

function <callback>(json) {
  // Use JSON data here
}

var jsonp = document.createElement("script");
jsonp.type = "application/javascript";
jsonp.href = "http://example.com?callback=<callback>";
document.head.appendChild(jsonp);

How JSONS works

JSONS allows cross-domain client-side transfer of JSON data without the problems accompanying the execution of arbitrary JavaScript code. It wraps the JSON data into a CSS style targeting an element (as specified in the request) which can then be read by the page's own JavaScript.

JSONS Request URL
http://example.com/api?id=<id>

JSONS Response Content
#<id> {display: none; content: '<json>'}

Usage (Client)

var element = document.createElement("span");
element.id = "<id>";
document.body.appendChild(element);

var jsons = document.createElement("link");
jsons.rel = "stylesheet";
jsons.type = "text/css";
jsons.href = "http://example.com?id=<id>";
jsons.addEventListener("load", function() {
  var style = window.getComputedStyle(element);
  var json = JSON.parse(style.content.slice(1, -1));
  // Use JSON data here
}, false);
document.head.appendChild(jsons);

Note: Apostrophes need to be escaped properly on either side of the transmission.

#json #css #jsonp
tweet
share