I recently needed to parse JSON from the command line. A GIS yielded a StackOverflow answer: jsawk.
There were other possibilities V8, Python, Perl and PHP, but a Javascript and Awk solution looked promising (and as a Javascript guy, the easiest to pickup). So after a bit of trial and error, here’s what worked for me.
[Edit- In the comments Bob Kuo suggested using Homebrew instead of MacPorts.]
Install MacPorts if you haven’t already.
# If you already had MacPorts installed, update and sync if necessary.
$ sudo port selfupdate $ sudo port sync
# Install SpiderMonkey (nspr is installed for you)
$ sudo port install spidermonkey
# Test your install
$ js
#You’ve been dropped into an interactive javascript shell, counts to 99
js> for(var a = 0; a < 100; a++){ print(a) }
# Quit.
js>quit()
# Install jsawk – you can put this wherever you like, I used ~/Code
# For more info, see https://github.com/micha/jsawk
$ mkdir ~/Code $ cd !$ $ curl -L http://github.com/micha/jsawk/raw/master/jsawk > jsawk $ sudo ln -s jsawk /usr/bin/jsawk
# Install resty
# For more info, see https://github.com/micha/resty
$ curl -L http://github.com/micha/resty/raw/master/resty > resty $ source resty
# View the current host (you can change this at anytime), outputs URL
$ resty
# For this demo, set the host to Twitter
$ resty http://api.twitter.com
# View host again to verify the change, outputs http://api.twitter.com/*
$ resty
# Get an array of dates from recent tweets on Twitter’s public timeline
$ resty GET /statuses/public_timeline.json | \ jsawk 'return this.created_at'
# Get my recent tweets
$ resty GET /statuses/user_timeline/johnattebury.json | \ jsawk 'return this.text'
Integrate jsawk into your shell scripts and you’ve got an excellent JSON parser ready for interesting problems. Combine jsawk with resty and a world of JSON api’s is just a prompt away.