Last active
October 13, 2015 17:47
-
-
Save tatat/4232543 to your computer and use it in GitHub Desktop.
JSON見やすく表示
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
#!/usr/bin/env ruby | |
require 'optparse' | |
require 'json' | |
$options = { | |
:print_type => false, | |
:print_each => true | |
} | |
opt = OptionParser.new | |
opt.on('-t') {|v| $options[:print_type] = true} | |
opt.on('-f') {|v| $options[:print_each] = false} | |
argv = opt.parse(ARGV); | |
def pretty_json(data, n = 0) | |
indent = ' ' | |
dir = indent * n | |
result = [] | |
case data | |
when Hash | |
if data.empty? | |
result << "{}" | |
else | |
result << "{" | |
data.each{|key, value| result << "#{dir + indent}#{key}: #{pretty_json(value, n + 1)}" } | |
result << "#{dir}}" | |
end | |
when Array | |
if data.empty? | |
result << "[]" | |
else | |
result << "[" | |
data.each do |value| | |
result << "#{dir + indent}#{pretty_json(value, n + 1)}" | |
break if $options[:print_type] || !$options[:print_each] | |
end | |
result << "#{dir}]" | |
end | |
when String | |
result << ($options[:print_type] ? '(String)' : data.to_json) | |
when Numeric | |
result << ($options[:print_type] ? '(Number)' : data.to_json) | |
else | |
result << ($options[:print_type] ? '(Null)' : data.to_json) | |
end.join("\n") | |
end | |
def print_json(input) | |
STDOUT.puts pretty_json(JSON.parse(input, :max_nesting => false)) | |
true | |
rescue | |
begin | |
STDOUT.puts JSON.parse("[#{input}]").first.to_json | |
true | |
rescue | |
STDERR.puts 'invalid json' | |
false | |
end | |
end | |
class LineReader | |
def initialize(stdin) | |
@buffer = '' | |
@stdin = stdin | |
end | |
def next | |
@buffer += @stdin.sysread(1) until @buffer[/\n/] | |
out, *others = @buffer.split("\n") | |
@buffer = others.join("\n") | |
out | |
rescue EOFError => ex | |
if @buffer == '' | |
nil | |
else | |
out = @buffer | |
@buffer = '' | |
out | |
end | |
end | |
def self.each | |
STDIN.sync = true | |
STDOUT.sync = true | |
instance = self.new(STDIN) | |
while line = instance.next | |
yield line | |
end | |
end | |
end | |
if not argv[0].nil? then | |
print_json argv[0] | |
elsif File.pipe?(STDIN) then | |
[:INT, :TERM].each do |signal| | |
trap(signal) do | |
STDERR.puts "got sig#{signal.to_s.downcase}" | |
exit | |
end | |
end | |
LineReader.each do |line| | |
print_json line | |
end | |
else | |
STDERR.puts "Usage: #{File.basename(__FILE__)} <json>" | |
exit 1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment