Skip to content

Instantly share code, notes, and snippets.

@PrimaryFeather
Last active March 16, 2018 07:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PrimaryFeather/873f0e413c8e0082eb2000f6e1a92f65 to your computer and use it in GitHub Desktop.
Save PrimaryFeather/873f0e413c8e0082eb2000f6e1a92f65 to your computer and use it in GitHub Desktop.
Small Ruby script that minifies (or un-minifies) JSON files.
#!/usr/bin/env ruby
require 'json'
script_name = File.basename(__FILE__)
prettify = false
if ARGV.count < 1
puts "Minifies JSON files."
puts ""
puts "Usage: #{script_name} file.json"
puts ""
puts "Options:"
puts " -p Prettify JSON instead."
exit
end
ARGV.each do |file|
if file == '-p' then
prettify = true
else
data_raw = File.read(file, encoding: 'bom|utf-8')
old_size = data_raw.length
new_size = 1
data = JSON.parse(data_raw)
File.open(file, 'w') do |f|
new_json = prettify ? JSON.pretty_generate(data) : JSON.generate(data)
new_size = new_json.length
f << new_json
end
compression = (new_size.to_f / old_size.to_f) * 100
puts " #{file} - ratio: #{'%.2f' % compression}%"
end
end
puts "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment