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 Ruby gem that will help us prettify output
gem install json
Now let’s grab a record from Facebook
$ curl graph.facebook.com/goodfordogs | prettify_json.rb
Produces the output (syntax highlighting by CodeRay)
{
"name": "GoodForDogs",
"category": "Local business",
"username": "Goodfordogs",
"id": "171644807551",
"website": "http://Goodfordogs.org",
"link": "http://www.facebook.com/Goodfordogs",
"likes": 871,
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs235.ash2/50503_171644807551_2269219_s.jpg"
}
Storing our JSON
The simplest solution is to save it to a file…
$ curl -s graph.facebook.com/goodfordogs | 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/goodfordogs -d @fb_gfd.json
{"ok":true,"id":"goodfordogs","rev":"1-f0422f8044e911b2f97c6ad71136eda1"}
# Check it's there
$ curl localhost:5984/facebook/goodfordogs | prettify_json.rb
Produces the JSON we stored with a couple of extra fields (id and rev)
{
"name": "GoodForDogs",
"category": "Local business",
"_rev": "1-f0422f8044e911b2f97c6ad71136eda1",
"username": "Goodfordogs",
"_id": "goodfordogs",
"id": "171644807551",
"website": "http://Goodfordogs.org",
"link": "http://www.facebook.com/Goodfordogs",
"picture": "http://profile.ak.fbcdn.net/hprofile-ak-snc4/hs235.ash2/50503_171644807551_2269219_s.jpg",
"likes": 871
}
Querying CouchDB is outside the scope of this tutorial
Posts in this series




