tuxdna tuxdna - 3 years ago 188
JSON Question

Prettify JSON data using Ruby on the terminal

I have earlier used Python for doing pretty output of JSON data like this:

python -mjson.tool input.json

I wanted to get similar output using Ruby. I am doing it like this:

ruby -rrubygems -e 'require "json"; ARGV.each { |f| print JSON.pretty_generate(JSON.load(File.open(f))) }' input.json

This is a lot for a small shell command. Can you suggest a better way?

Answer Source

You can shorten your script:

# ruby 1.9.2
ruby -rjson -e 'ARGF.each(nil) {|f| puts JSON.pretty_generate(JSON.parse(f)) }'  file1 file2 

# ruby 1.8.7
ruby -rubygems -e 'require "json"; ARGF.each(nil) {|f| puts JSON.pretty_generate(JSON.parse(f)) }'  file1 file2 

ARGF is a stream designed for use in scripts that process files given as command-line arguments or passed in via STDIN.

I pass nil to ARGF#each method to split ARGF by files, not by lines (default behavior of #each).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download