Class: PrettifyJson::JsonPrettifier

Inherits:
Object
  • Object
show all
Defined in:
lib/prettify_json.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(json_string) ⇒ JsonPrettifier



10
11
12
# File 'lib/prettify_json.rb', line 10

def initialize(json_string)
  @json_string = json_string
end

Instance Attribute Details

#json_stringObject (readonly)

Returns the value of attribute json_string.



8
9
10
# File 'lib/prettify_json.rb', line 8

def json_string
  @json_string
end

Instance Method Details

#colorize_json(json_string) ⇒ Object



14
15
16
17
18
# File 'lib/prettify_json.rb', line 14

def colorize_json(json_string)
  regex = /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(?:\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/

  json_string.gsub(regex) { |match| colorize_match(match) }
end

#colorize_match(match) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/prettify_json.rb', line 20

def colorize_match(match)
  case match
  when /^"/
    match.include?(':') ? Rainbow(match).yellow : Rainbow(match).green
  when 'true', 'false'
    Rainbow(match).blue
  when 'null'
    Rainbow(match).magenta
  else
    Rainbow(match).red
  end
end

#pretty_printObject



33
34
35
36
37
38
39
# File 'lib/prettify_json.rb', line 33

def pretty_print
  parsed_json = JSON.parse(json_string)
  pretty_json = JSON.pretty_generate(parsed_json)
  colorize_json(pretty_json)
rescue JSON::ParserError => e
  "Invalid JSON: #{e.message}"
end