Pretty JSON in and out of Ruby

Parallel to Ruby’s p and pp methods for quickly printing and pretty-printing, Ruby’s JSON library offers j and jj methods for quickly printing objects in JSON format:

> obj = {"foo"=>"bar", "baz"=>[1, 2, 3]}

> p obj
{"foo"=>"bar", "baz"=>[1, 2, 3]}

> j obj

> jj obj
  "foo": "bar",
  "baz": [

Definitely handy for investigating those large, deeply-nested objects.

I’ve not actually looked, but the implementation of jj is probably just something like…

def my_jj(obj)
  puts JSON.pretty_generate(obj)

…which I point out in case you want to do something slightly different like send the pretty output to a log.

What if we have a snippet of JSON in a file that we’d like to have pretty printed? It’s pretty easy to whip up a little command-line filter:

#!/usr/bin/env ruby
# jj.rb - pretty print JSON from file or standard input

require 'json'

jj JSON[]

Gotta love Ruby. :)

$ curl | ./jj.rb
    "in_reply_to_status_id_str": null,
    "created_at": "Fri Feb 10 20:33:12 +0000 2012",
    "possibly_sensitive": false,
    "in_reply_to_user_id_str": null,
    "place": null,
    "in_reply_to_user_id": null,
    "in_reply_to_screen_name": null,
    "id_str": "168070028388864000",
    "in_reply_to_status_id": null,
    "contributors": null,
    "user": {
      "default_profile": false,
      "show_all_inline_media": true,