A simple CoffeeScript to JSON shell script for Macs

I was working through a tutorial on Bogart and CouchDB and decided to implement the examples in CoffeeScript instead of JavaScript as I've been meaning to play with CoffeeScript for a while now.

One of the files in the tutorial is the package.json file for managing dependencies in the (absolutely lovely) package manager npm. When I wrote the data structure out in CoffeeScript, however, the compiled data structure wasn't valid JSON according to JSONLint (it was nested between parentheses, had unquoted keys, and a trailing semi-colon, as you can see in the code snippet.)

  name: "blog",

(The CoffeeScript compiler generated the surrounding parentheses even when I used the --bare compiler flag.)

The resulting file also had a .js extension, instead of a .json extension and I couldn't find a way to change that (although there is a compiler flag to change the folder the file gets created in).

So, to cut a long story short, I just whipped up a little shell script to convert my original CoffeeScript data structure into valid JSON simply by removing the extra characters the compiler had thrown in and adding quotes around the keys. Here's the (pardon the pun) gist of it:

(Update: Thanks to Max's comment, I was able to boil down the script to a single line and get rid of the temporary files – thanks, Max!)

Not rocket science and I'm not a sed wizard so it may not be the most efficient way of doing things but it works.

So, if you want to write your static data structures in CoffeeScript and have them compile into valid JSON:

  1. check out the gist
  2. Save it in a file called coffeetojson
  3. Don't forget to chmod +x coffeetojson to make it executable
  4. Then, assuming that the coffeetojson script is in the same folder as your .coffee script containing your data structure (let's assume it's in a file called mydata.coffee), enter the following:

./coffeetojson mydata

That will create a file called mydata.json with the valid JSON version of your data structure. (I haven't tested this exhaustively at all so there's a big chance it might fail – if it does, I'll be very happy to receive your patches.) :)

Why go to all this trouble, instead of authoring JSON by hand initially? Well, because as easy as JSON is to author by hand, CoffeeScript – with its barer syntax – is simpler still. And I'm lazy! :-)

Here's hoping this helps someone out there who is as lazy as I am!