2 # Returns a JSON string representing the hash.
4 # Without any +options+, the returned JSON string will include all
5 # the hash keys. For example:
7 # { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json
8 # # => {"name": "Konata Izumi", 1: 2, "age": 16}
10 # The keys in the JSON string are unordered due to the nature of hashes.
12 # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the
13 # attributes included, and will accept 1 or more hash keys to include/exclude.
15 # { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json(:only => [:name, 'age'])
16 # # => {"name": "Konata Izumi", "age": 16}
18 # { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json(:except => 1)
19 # # => {"name": "Konata Izumi", "age": 16}
21 # The +options+ also filter down to any hash values. This is particularly
22 # useful for converting hashes containing ActiveRecord objects or any object
23 # that responds to options in their <tt>to_json</tt> method. For example:
25 # users = User.find(:all)
26 # { :users => users, :count => users.size }.to_json(:include => :posts)
28 # would pass the <tt>:include => :posts</tt> option to <tt>users</tt>,
29 # allowing the posts association in the User model to be converted to JSON
31 def to_json(options
= {}) #:nodoc:
35 hash_keys
= hash_keys
- Array(options
[:except])
37 hash_keys
= hash_keys
& Array(options
[:only])
40 returning result
= '{' do
41 result
<< hash_keys
.map
do |key
|
42 "#{ActiveSupport::JSON.encode(key)}: #{ActiveSupport::JSON.encode(self[key], options)}"