Last active
March 16, 2018 07:30
-
-
Save PrimaryFeather/873f0e413c8e0082eb2000f6e1a92f65 to your computer and use it in GitHub Desktop.
Small Ruby script that minifies (or un-minifies) JSON files.
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
#!/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