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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
# File 'lib/sidekiq_bus/server.rb', line 20
def parse_query(query_string)
has_open_brace = query_string.include?("{")
has_close_brace = query_string.include?("}")
has_multiple_lines = query_string.include?("\n")
has_colon = query_string.include?(":")
has_comma = query_string.include?(",")
has_quote = query_string.include?("\"")
exception = nil
begin
query_attributes = JSON.parse(query_string)
raise "Not a JSON Object" unless query_attributes.is_a?(Hash)
rescue Exception => e
exception = e
end
return query_attributes unless exception
if query_attributes
if query_attributes.is_a?(Array) && query_attributes.length == 1
json_string = query_attributes.first
fixed = JSON.parse(json_string) rescue nil
return fixed if fixed
end
raise exception
end
if !has_open_brace && !has_close_brace
fixed = JSON.parse("{ #{query_string} }") rescue nil
return fixed if fixed
end
if !has_open_brace
fixed = JSON.parse("{ #{query_string}") rescue nil
return fixed if fixed
end
if !has_close_brace
fixed = JSON.parse("#{query_string} }") rescue nil
return fixed if fixed
end
if !has_multiple_lines && !has_colon && !has_open_brace && !has_close_brace
return {"bus_event_type" => query_string, "more_here" => true}
end
if has_colon && !has_quote
test_query = query_string.gsub(/([a-zA-z]\w*)/,'"\0"')
if !has_comma
test_query.gsub!("\n", ",\n")
end
if !has_open_brace && !has_close_brace
test_query = "{ #{test_query} }"
end
fixed = JSON.parse(test_query) rescue nil
return fixed if fixed
end
if has_open_brace && has_close_brace
ruby_hash_text = query_string.clone
ruby_hash_text.gsub!(/([{,]\s*):([^>\s]+)\s*=>/, '\1"\2"=>')
ruby_hash_text.gsub!(/([{,]\s*)([0-9]+\.?[0-9]*)\s*=>/, '\1"\2"=>')
ruby_hash_text.gsub!(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>\s*:([^,}\s]+\s*)/, '\1\2=>"\3"')
ruby_hash_text.gsub!(/([\[,]\s*):([^,\]\s]+)/, '\1"\2"')
ruby_hash_text.gsub!(/=>nil/, '=>null')
ruby_hash_text.gsub!(/([{,]\s*)(".+?"|[0-9]+\.?[0-9]*)\s*=>/, '\1\2:')
fixed = JSON.parse(ruby_hash_text) rescue nil
return fixed if fixed
end
raise exception
end
|