Skip to content

Instantly share code, notes, and snippets.

@tarot
Created October 6, 2015 19:52
Show Gist options
  • Save tarot/b9103395a96488aec93c to your computer and use it in GitHub Desktop.
Save tarot/b9103395a96488aec93c to your computer and use it in GitHub Desktop.
空配列と空ハッシュで改行しないJSON.pretty_generate モンキーパッチ版
require 'json'
require 'json/pure/generator'
module JSON::Pure::Generator::GeneratorMethods
%i(Fixnum Bignum).each do |constant|
const_set constant, Integer
end
module Array
alias_method :pure_to_json, :to_json
def to_json(state = nil, *)
empty? ? '[]' : pure_to_json(state)
end
end
module Hash
alias_method :pure_to_json, :to_json
def to_json(state = nil, *)
empty? ? '{}' : sort.to_h.pure_to_json(state)
end
end
remove_const :Integer
end
desc 'normalize a.json'
task :normalize do
filename = 'a.json'
JSON.generator = JSON::Pure::Generator
src = File.open(filename) { |io| JSON.load(io) }
File.open(filename, 'w') { |io| io.write(JSON.pretty_generate(src)) }
end
@tarot
Copy link
Author

tarot commented Oct 6, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment