Skip to content

json

JSON in your Web Browser

Web browsers don't tend to display JSON very nicely. See how yours does with this example. Some handy plugins that help with this. While they currently only allow viewing, how long before we se some PUT/POST action?

JSONView for Firefox

Normally when encountering a JSON document (content type "application/json"), Firefox simply prompts you to download the file. With the JSONView extension, JSON documents are shown in the browser similar to how XML documents are shown. The document is formatted, highlighted, and arrays and objects can be collapsed. Even if the JSON document contains errors, JSONView will still show the raw text.

There is also an Unofficial JSONView port for Chrome and the Unfortunately Named "XML View" for Safari

When installed, your JSON will look more like this:

JSONView browser plugins prettify JSONView browser plugins prettify

Posts in this series:

JSON with Ruby and Rails

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.

Ruby support for JSON

Ruby's JSON library makes parsing and generating JSON simple.

Converting between hash and json in Ruby

$ irb
>> require 'json'
=> true
>> json_text = { :name => 'Mike', :age => 70 }.to_json
=> "{\"name\":\"Mike\",\"age\":70}"
>> JSON.parse(json_text)
=> {"name"=>"Mike", "age"=>70}

HTTParty helps with communicating with RESTful services

Here we grab a record from Facebook.

Retrieve a JSON Resource

$ irb
>> require 'awesome_print'
=> true
>> require 'json'
=> true
>> require 'httparty'
=> true
>> ap JSON.parse HTTParty.get('https://graph.facebook.com/Stoptheclock').response.body
{
                  "about" => "Abolish the 28 Day Rule for Victorian Shelters\n\nhttp://stoptheclock.com.au\n\ninfo@stoptheclock.com.au",
               "category" => "Community",
                "founded" => "2010",
           "is_published" => true,
                "mission" => "To bring an end to the law requiring Victorian shelters to kill healthy adoptable cats and dogs after four weeks.",
    "talking_about_count" => 3,
               "username" => "Stoptheclock",
                "website" => "http://stoptheclock.com.au",
        "were_here_count" => 0,
                     "id" => "167163086642552",
                   "name" => "Stop The Clock",
                   "link" => "http://www.facebook.com/Stoptheclock",
                  "likes" => 5517
}
=> nil

HTTParty gets Classy

Creating a simple class allows you to DRY things up a bit

$ irb
>> require 'httparty'
=> true
>> class Facebook
>>   include HTTParty
>>   base_uri 'https://graph.facebook.com/'
>>   # default_params :output => 'json'
?>   format :json
>>
?>   def self.object(id)
>>     get "/#{id}"
>>   end
>> end
=> nil
>>
>> require 'awesome_print'
>> ap Facebook.object('Stoptheclock').parsed_response
{
                  "about" => "Abolish the 28 Day Rule for Victorian Shelters\n\nhttp://stoptheclock.com.au\n\ninfo@stoptheclock.com.au",
               "category" => "Community",
                "founded" => "2010",
           "is_published" => true,
                "mission" => "To bring an end to the law requiring Victorian shelters to kill healthy adoptable cats and dogs after four weeks.",
    "talking_about_count" => 3,
               "username" => "Stoptheclock",
                "website" => "http://stoptheclock.com.au",
        "were_here_count" => 0,
                     "id" => "167163086642552",
                   "name" => "Stop The Clock",
                   "link" => "http://www.facebook.com/Stoptheclock",
                  "likes" => 5517
}
=> nil

Rails support for JSON

ActiveSupport::JSON knows how to convert ActiveRecord objects (and more) to JSON. Simone Carletti explains how this differs from the standard lib.

## Encode
json = ActiveSupport::JSON.encode(object) # extra methods like :include
json = Offering.first.to_json(:include => :outlet, :methods => [:days_waiting])

## Decode
ActiveSupport::JSON.decode(json)

Rails3 niceness

Adding JSON to your Rails3 app doesn't require a lot of extra code. You can specify method calls and associated objects to include as well as restrict the attributes returned. Simple eh?

class PostController < ApplicationController
  respond_to :json, :html, :jpg, :xml

  def index
    respond_with(@posts = Post.all),
                   :methods => [:average_rating],
                   :include => :comments
  end

  def show
    respond_with(@post = Post.find(params[:id])), :only => [:name, :body]
  end

end

Posts in this series

JSON from Javascript

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.

Someone on StackOverflow reckons Internet Explorer 8, Firefox 3.5+, Safari 4+, Chrome, and Opera 10+ support native JSON parsing. Douglas Crockford's json2.js library adds the standard JSON methods to browsers that lack them. jQuery's JSON parser makes use of the browsers native implementation where this is one.

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 Javascript
myJSONtext = '{"name":"mike","species":"human"}'

// Parse JSON
reviver = null;
myObject = JSON.parse(myJSONtext, reviver);
myObject.species // => 'human'

// Generate JSON
replacer = null
myNewJSONtext = 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.

// JSONP gets around 'same origin policy'
// jQuery generates randomly named callback function
var returnVal = '';
var ajaxUrl = 'https://graph.facebook.com/goodfordogs?callback=?';
// var ajaxUrl = 'http://localhost:5984/facebook/goodfordogs?callback=?';
$.getJSON(ajaxUrl, null, function(data) {
  alert(data.likes + ' people like '+ data.name);
});

var returnVal = '';
var ajaxUrl = 'https://graph.facebook.com/goodfordogs?callback=?';
// var ajaxUrl = 'http://localhost:5984/facebook/goodfordogs?callback=?';
$.getJSON(ajaxUrl, null, function(data) {
  alert(data.likes + ' people like '+ data.name);
});

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:

$ curl graph.facebook.com/goodfordogs?callback=blah
blah({
   "id": "171644807551",
   "name": "GoodForDogs",
   "picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/50503_171644807551_2269219_s.jpg",
   "link": "http://www.facebook.com/Goodfordogs",
   "category": "Local business",
   "website": "http://Goodfordogs.org",
   "username": "Goodfordogs",
   "likes": 902
});

jQuery picks a random name for the callback to make things easier for you. In fact it does a pretty good job of hiding the inner workings of JSONP from you.

Posts in this series:

JSON from the Command Line

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.

Syntax Highlighting for Vim

Useful when writing or editing JSON. Grab it here and drop into ~/.vim/plugin/

Consuming with CURL

Disable curl's progress bar and enable compression

$ echo "silent=true" >> ~/.curlrc
$ echo "compressed=true" >> ~/.curlrc

Install a Node.js package that will help us prettify output

npm install -g jsontool

Now let's grab a record from Facebook

$ curl graph.facebook.com/stoptheclock | json
{
  "about": "Abolish the 28 Day Rule for Victorian Shelters\n\nhttp://stoptheclock.com.au\n\ninfo@stoptheclock.com.au",
  "category": "Community",
  "founded": "2010",
  "is_published": true,
  "mission": "To bring an end to the law requiring Victorian shelters to kill healthy adoptable cats and dogs after four weeks.",
  "talking_about_count": 2,
  "username": "Stoptheclock",
  "website": "http://stoptheclock.com.au",
  "were_here_count": 0,
  "id": "167163086642552",
  "name": "Stop The Clock",
  "link": "http://www.facebook.com/Stoptheclock",
  "likes": 5515
}

Storing our JSON

The simplest solution is to save it to a file...

$ curl -s graph.facebook.com/stoptheclock | prettify_json.rb > fb_gfd.json

...but other applications can accept JSON such as CouchDB

Here we'll create a new database, store our JSON to it and then retrieve it.

# Create a database on CouchDB
$ curl localhost:5984/_all_dbs-X PUT localhost:5984/facebook
{"ok":true}

# Check it's there
$ curl localhost:5984/_all_dbs
["facebook","test"]

# Save our document to it
$ curl -X PUT localhost:5984/facebook/stoptheclock -d @fb_stc.json
{"ok":true,"id":"stoptheclock","rev":"1-f0422f8044e911b2f97c6ad71136eda1"}

# Check it's there
$ curl localhost:5984/facebook/stoptheclock | json
{
  "about": "Abolish the 28 Day Rule for Victorian Shelters\n\nhttp://stoptheclock.com.au\n\ninfo@stoptheclock.com.au",
  "category": "Community",
  "_rev": "1-f0422f8044e911b2f97c6ad71136eda1",
  "_id": "stoptheclock",
  "founded": "2010",
  "is_published": true,
  "mission": "To bring an end to the law requiring Victorian shelters to kill healthy adoptable cats and dogs after four weeks.",
  "talking_about_count": 2,
  "username": "Stoptheclock",
  "website": "http://stoptheclock.com.au",
  "were_here_count": 0,
  "id": "167163086642552",
  "name": "Stop The Clock",
  "link": "http://www.facebook.com/Stoptheclock",
  "likes": 5515
}

Querying CouchDB is outside the scope of this tutorial

How do I query the data now it's in CouchDB? How do I query the data now it's in CouchDB?

Posts in this series: