SpiderMonkey, jsawk & resty on Snow Leopard

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.

Advertisements

4 thoughts on “SpiderMonkey, jsawk & resty on Snow Leopard

  1. Hi, nice post! If you like the vi editor you might be into something likennGET /the/path | jsawk ‘do_something()’ | PUT -VnnIt opens a vi editor with the result of the GET so you can edit it, and when you save it uses that as the data for the PUT.nnCheers!

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s