Skip to content

Instantly share code, notes, and snippets.

Created September 17, 2012 18:37
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Ruby script to pretty print JSON on the command line (comes with Ruby's json Gem)
#!/usr/bin/env ruby
require 'json'
require 'fileutils'
include FileUtils
# Parses the argument array _args_, according to the pattern _s_, to
# retrieve the single character command line options from it. If _s_ is
# 'xy:' an option '-x' without an option argument is searched, and an
# option '-y foo' with an option argument ('foo').
# An option hash is returned with all found options set to true or the
# found option argument.
def go(s, args = ARGV)
b, v = s.scan(/(.)(:?)/).inject([{},{}]) { |t,(o,a)|
t[a.empty? ? 0 : 1][o] = a.empty? ? false : nil
while a = args.shift
a !~ /\A-(.+)/ and args.unshift a and break
p = $1
until p == ''
o = p.slice!(0, 1)
if v.key?(o)
v[o] = if p == '' then args.shift or break 1 else p end
elsif b.key?(o)
b[o] = true
args.unshift a
break 1
end and break
opts = go 'slhi:', args = ARGV.dup
if opts['h'] || opts['l'] && opts['s']
puts <<EOT
Usage: #{File.basename($0)} [OPTION] [FILE]
If FILE is skipped, this scripts waits for input from STDIN. Otherwise
FILE is opened, read, and used as input for the prettifier.
OPTION can be
-s to output the shortest possible JSON (precludes -l)
-l to output a longer, better formatted JSON (precludes -s)
-i EXT prettifies FILE in place, saving a backup to FILE.EXT
-h this help
exit 0
filename = nil
json = JSON[
if args.empty?
else filename = args.first
output = if opts['s']
JSON.fast_generate json
else # default is -l
JSON.pretty_generate json
if opts['i'] && filename
cp filename, "#{filename}.#{opts['i']}", 'w') { |f| f.puts output }
puts output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment