Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 62 lines (57 sloc) 1.233 kB
db9a764 @Manfred Complete the switch to JSON.
Manfred authored
1 module JSON
2 REPLACEMENTS = {
3 '\\' => '\\\\',
4 '"' => '\\"',
5 '/' => '\/',
6 "\b" => '\\b',
7 "\f" => '\\f',
8 "\n" => '\\n',
9 "\r" => '\\r',
10 "\t" => '\\t'
11 }
12
13 def self.generate(object)
14 serialize(object)
15 end
16
17 def self.serialize(object)
18 case object
19 when Hash
20 self._serialize_hash(object)
21 when Array
22 self._serialize_array(object)
23 when String
24 self._serialize_string(object)
25 when FalseClass
26 'false'
27 when TrueClass
28 'true'
29 when NilClass
30 'null'
31 else
32 object.respond_to?(:to_json) ? object.to_json : object.to_s
33 end
34 end
35
36 def self._serialize_string(object)
37 escaped = object.gsub(/[\\\"\/\b\f\n\r\t]/) do |match|
38 REPLACEMENTS[match]
39 end
40 "\"#{escaped}\""
41 end
42
43 def self._serialize_hash(object)
44 out = '{'
45 first = true
46 for name, value in object
47 first ? first = false : out << ','
48 out << JSON.serialize(name) << ':' << JSON.serialize(value)
49 end
50 out << '}'
51 end
52
53 def self._serialize_array(object)
54 out = '['
55 first = true
56 for value in object
57 first ? first = false : out << ','
58 out << JSON.serialize(value)
59 end
60 out << ']'
61 end
62 end
Something went wrong with that request. Please try again.