JSON from Javascript

2 minute read

JSON is a beautiful format for storing objects as human readable text. It’s
succeeded where XML has failed. Not only is it not shit, it’s actually quite
good! But don’t just take my word for it, have a look at some of the “cool”
ways you can generate and consume JSON.

JSON support added to Javascript

JSON is an acronym for Javascript Object Notation and while it’s designed for
data interchange it’s a string containing valid Javascript. While you could
instantiate the object using eval, executing data is like eating off food off
the ground - unhygienic and with unknown side effects. Fortunately support for
JSON was added to ECMAscript 5 so you can generate and parse JSON without fear.

Enough yakking, time for a demo

This is using native Javascript to generate and consume JSON. You can run this
stuff in Firebug. Sorry, I don’t have any CSS to make it look all “firebuggy”.
Does anyone know of a Javascript interpreter I can run in a shell?

// Basic JavascriptmyJSONtext='{"name":"mike","species":"human"}'// Parse JSONreviver=null;myObject=JSON.parse(myJSONtext,reviver);myObject.species// => 'human'// Generate JSONreplacer=nullmyNewJSONtext=JSON.stringify(myObject,replacer);myJSONtext==myNewJSONtext// They should be the same

jQuery support for JSON

Open Firefox to any webpage that loads jQuery (e.g. jquery.com) and paste this into your Firebug console.

Web browsers prevent Javascript from sending requests to domains other than the
originating one. So you can’t get your AJAX request to simply request a JSON
object from Facebook. A neat way around this is to write script tags to the
document that load a remote javascript file. JSONP lets us specify a callback
that will be called with the resultant JSON. It’s easier to show you: