3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
# File 'lib/forest_liana/json_printer.rb', line 3
def pretty_print json, indentation = ""
result = ""
if json.kind_of? Array
result << "["
is_small = json.length < 3
is_primary_value = false
json.each_index do |index|
item = json[index]
is_primary_value = !item.kind_of?(Hash) && !item.kind_of?(Array)
if index == 0 && is_primary_value && !is_small
result << "\n#{indentation} "
elsif index > 0 && is_primary_value && !is_small
result << ",\n#{indentation} "
elsif index > 0
result << ", "
end
result << pretty_print(item, is_primary_value ? "#{indentation} " : indentation)
end
result << "\n#{indentation}" if is_primary_value && !is_small
result << "]"
elsif json.kind_of? Hash
result << "{\n"
is_first = true
json = json.stringify_keys
json.each do |key, value|
result << ",\n" unless is_first
is_first = false
result << "#{indentation} \"#{key}\": "
result << pretty_print(value, "#{indentation} ")
end
result << "\n#{indentation}}"
elsif json.nil?
result << "null"
elsif !!json == json
result << (json ? "true" : "false")
elsif json.is_a?(String) || json.is_a?(Symbol)
result << "\"#{json.gsub(/"/, '\"')}\""
else
result << json.to_s
end
result
end
|