Class: Jsonpretty

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonpretty.rb,
lib/jsonpretty/version.rb

Constant Summary collapse

VERSION =
"1.2.0"

Instance Method Summary collapse

Instance Method Details

#clean_jsonp(input_string) ⇒ Object



26
27
28
29
30
31
32
33
34
# File 'lib/jsonpretty.rb', line 26

def clean_jsonp(input_string)
  match = input_string.match(/^(.+)\((.+)\)$/)
  if match
    puts "jsonp method name: #{match[1]}\n\n"
    match[2]
  else
    input_string
  end
end

#file_value(filename) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/jsonpretty.rb', line 4

def file_value(filename)
  file = if filename == '-'
           $stdin
         else
           File.open(filename)
         end
  lines = file.readlines
  if lines.first =~ /^HTTP\/\d/ # looks like an HTTP response; we just want the body
    index = lines.index("\r\n") || lines.index("\n")
    puts lines[0..index]
    lines[(index+1)..-1].join('')
  else
    lines.join('')
  end
ensure
  file.close
end

#mainObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/jsonpretty.rb', line 36

def main
  if ARGV.length == 0
    ARGV.unshift stdin_value
  else
    ARGV.each_with_index do |v,i|
      case v
      when /^--?h/
        puts("usage: #{File.basename($0)} [args|@filename|@- (stdin)]",
             "Parse and pretty-print JSON, either from stdin or from arguments concatenated together")
        exit 0
      when /^--?v/
        puts "jsonpretty version #{VERSION}"
        exit 0
      else
        if v == '-'
          ARGV[i] = stdin_value
        elsif v =~ /^@/
          ARGV[i] = file_value(v[1..-1])
        end
      end
    end
  end

  input = clean_jsonp(ARGV.join(' '))
  json = JSON.parse(input)
  puts JSON.pretty_generate(json)
rescue => e
  $stderr.puts "jsonpretty failed: #{e.message}"
  exit 1
end

#stdin_valueObject



22
23
24
# File 'lib/jsonpretty.rb', line 22

def stdin_value
  file_value('-')
end