Created
October 26, 2013 22:46
-
-
Save EronHennessey/7175471 to your computer and use it in GitHub Desktop.
Clean JSON. Takes messy JSON and makes it much nicer looking. Use it with a json file passed in as a command-line argument or via standard input, thanks to the magic of Ruby's built-in 'json' library and pretty_generate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Clean JSON. Takes messy JSON and makes it much nicer looking. | |
# | |
# Usage: | |
# | |
# ruby cleanjson.rb <infile> <outfile> | |
# | |
# Reads the JSON-formatted text in <infile> and outputs the cleaned JSON to | |
# <outfile>. | |
# | |
# Both arguments are optional, but you cannot specify an <outfile> without | |
# specifying an <infile>. | |
# | |
# You can use this with streaming input/output, such as: | |
# | |
# cat file.json | ruby cleanjson.rb | |
# | |
# or | |
# | |
# ruby cleanjson.rb <file.json >file_cleaned.json | |
# | |
# ...of course, the standard file-based syntax is 2 fewer characters to type | |
# than this. | |
# | |
# However, using this script as a pipe allows you to do nice things such as take | |
# messy JSON output from a script and pipe it through this to make it easier to | |
# read. | |
# | |
require 'json' | |
json_file, json_out_file = ARGV | |
json_text = nil | |
unless json_file.nil? | |
if File.exist?(json_file) | |
json_text = File.new(json_file, 'r').read | |
else | |
puts "File #{json_file} does not exist!" | |
exit | |
end | |
else | |
json_text = $stdin.read | |
end | |
data = JSON.parse(json_text) | |
json_text = JSON.pretty_generate(data) | |
unless json_out_file.nil? | |
f = File.new(json_out_file, 'w+') | |
f.write(json_text) | |
f.close | |
else | |
$stdout.puts json_text | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment