Class: JSON

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

Overview

Ruby implementation of JSON serialization.

JSON.serialize([{'title' => 'Tron'}, 12]) # => "[{"title":"Tron"},12]"

Constant Summary collapse

REPLACEMENTS =
{
  '\\' => '\\\\',
  '"'  => '\\"',
  '/'  => '\/',
  "\b" => '\\b',
  "\f" => '\\f',
  "\n" => '\\n',
  "\r" => '\\r',
  "\t" => '\\t'
}

Class Method Summary collapse

Class Method Details

.serialize(object) ⇒ Object Also known as: generate

Serializes a Ruby object to a valid JSON expression.

JSON.serialize({'title' => 'Tron'}) # => '{"title":"Tron"}'

You can serialize unsupported classes by defining the to_json method on them.

class Person
  attr_accessor :name
  def to_json
    JSON.serialize(name)
  end
end


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/crock.rb', line 29

def self.serialize(object)
  case object
  when Hash
    self.serialize_hash(object)
  when Array
    self.serialize_array(object)
  when String
    self.serialize_string(object)
  when FalseClass
    'false'
  when TrueClass
    'true'
  when NilClass
    'null'
  else
    object.respond_to?(:to_json) ? object.to_json : object.to_s
  end
end