Changeset 8010
- Timestamp:
- 10/24/07 16:21:46 (7 months ago)
- Files:
-
- trunk/activesupport/CHANGELOG (modified) (1 diff)
- trunk/activesupport/lib/active_support/json/encoders/enumerable.rb (modified) (1 diff)
- trunk/activesupport/lib/active_support/json/encoders/hash.rb (modified) (1 diff)
- trunk/activesupport/test/json/encoding_test.rb (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
- Modified
- Copied
- Moved
trunk/activesupport/CHANGELOG
r7997 r8010 1 1 *SVN* 2 3 * Document Enumerable and Hash #to_json. #9970 [Chu Yeow] 2 4 3 5 * Hash#to_xml handles symbol values. #9954 [Assaf] trunk/activesupport/lib/active_support/json/encoders/enumerable.rb
r7736 r8010 1 1 module Enumerable 2 # Returns a JSON string representing the enumerable. Any +options+ 3 # given will be passed on to its elements. For example: 4 # 5 # users = User.find(:all) 6 # users.to_json(:only => :name) 7 # 8 # will pass the <tt>:only => :name</tt> option to each user. 2 9 def to_json(options = {}) #:nodoc: 3 10 "[#{map { |value| ActiveSupport::JSON.encode(value, options) } * ', '}]" trunk/activesupport/lib/active_support/json/encoders/hash.rb
r7736 r8010 1 1 class Hash 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. 2 34 def to_json(options = {}) #:nodoc: 3 35 hash_keys = self.keys trunk/activesupport/test/json/encoding_test.rb
r7746 r8010 46 46 assert_equal %({\"a\": 1}), { 'a' => 1 }.to_json 47 47 assert_equal %({\"a\": [1, 2]}), { 'a' => [1,2] }.to_json 48 assert_equal %({1: 2}), { 1 => 2 }.to_json 48 49 49 50 sorted_json = '{' + {:a => :b, :c => :d}.to_json[1..-2].split(', ').sort.join(', ') + '}'