Projects by
Thomas Greiner blog
web log
Proof-of-Concept Projects

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

JSONP Response Content

Usage (Client)

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

var jsonp = document.createElement("script");
jsonp.type = "application/javascript";
jsonp.href = "<callback>";

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

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

Usage (Client)

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

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

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

#json #css #jsonp