camdez.com

Rule #1: There are no rules.

Pretty JSON in and Out of Ruby

| Comments

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
> obj = {"foo"=>"bar", "baz"=>[1, 2, 3]}

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

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

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

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

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

1
2
3
def my_jj(obj)
  puts JSON.pretty_generate(obj)
end

…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:

(jj.rb) download
1
2
3
4
5
6
#!/usr/bin/env ruby
# jj.rb - pretty print JSON from file or standard input

require 'json'

jj JSON[ARGF.read]

Gotta love Ruby. :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ curl http://twitter.com/statuses/public_timeline.json | ./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,
(...)

Comments