Created
October 6, 2015 19:52
-
-
Save tarot/b9103395a96488aec93c to your computer and use it in GitHub Desktop.
空配列と空ハッシュで改行しないJSON.pretty_generate モンキーパッチ版
This file contains hidden or 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
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
forked from https://gist.github.com/tarot/01789a80de9cfaa117f2