| | 2 | # Returns a JSON string representing the hash. |
|---|
| | 3 | # |
|---|
| | 4 | # Without any +options+, the returned JSON string will include all |
|---|
| | 5 | # the hash keys. For example: |
|---|
| | 6 | # |
|---|
| | 7 | # { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json |
|---|
| | 8 | # |
|---|
| | 9 | # {"name": "Konata Izumi", 1: 2, "age": 16} |
|---|
| | 10 | # |
|---|
| | 11 | # The keys in the JSON string are unordered due to the nature of hashes. |
|---|
| | 12 | # |
|---|
| | 13 | # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the |
|---|
| | 14 | # attributes included, and will accept 1 or more hash keys to include/exclude. |
|---|
| | 15 | # |
|---|
| | 16 | # { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json(:only => [:name, 'age']) |
|---|
| | 17 | # |
|---|
| | 18 | # {"name": "Konata Izumi", "age": 16} |
|---|
| | 19 | # |
|---|
| | 20 | # { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json(:except => 1) |
|---|
| | 21 | # |
|---|
| | 22 | # {"name": "Konata Izumi", "age": 16} |
|---|
| | 23 | # |
|---|
| | 24 | # The +options+ also filter down to any hash values. This is particularly |
|---|
| | 25 | # useful for converting hashes containing ActiveRecord objects or any object |
|---|
| | 26 | # that responds to options in their <tt>to_json</tt> method. For example: |
|---|
| | 27 | # |
|---|
| | 28 | # users = User.find(:all) |
|---|
| | 29 | # { :users => users, :count => users.size }.to_json(:include => :posts) |
|---|
| | 30 | # |
|---|
| | 31 | # would pass the <tt>:include => :posts</tt> option to <tt>users</tt>, |
|---|
| | 32 | # allowing the posts association in the User model to be converted to JSON |
|---|
| | 33 | # as well. |
|---|