Properly quote json keys.

According to the RFC and the json.org site all json keys must be strings, and those strings must be quoted with double quotes.
[#1755 state:committed]
This commit is contained in:
Michael Koziarski 2009-01-16 17:37:36 +13:00
parent a53ad5bba3
commit 0bed5bdb21
2 changed files with 4 additions and 4 deletions

View File

@ -5,7 +5,7 @@ class Hash
# the hash keys. For example: # the hash keys. For example:
# #
# { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json # { :name => "Konata Izumi", 'age' => 16, 1 => 2 }.to_json
# # => {"name": "Konata Izumi", 1: 2, "age": 16} # # => {"name": "Konata Izumi", "1": 2, "age": 16}
# #
# The keys in the JSON string are unordered due to the nature of hashes. # The keys in the JSON string are unordered due to the nature of hashes.
# #
@ -39,7 +39,7 @@ class Hash
returning result = '{' do returning result = '{' do
result << hash_keys.map do |key| result << hash_keys.map do |key|
"#{ActiveSupport::JSON.encode(key)}: #{ActiveSupport::JSON.encode(self[key], options)}" "#{ActiveSupport::JSON.encode(key.to_s)}: #{ActiveSupport::JSON.encode(self[key], options)}"
end * ', ' end * ', '
result << '}' result << '}'
end end

View File

@ -59,7 +59,7 @@ class TestJSONEncoding < Test::Unit::TestCase
assert_equal %({\"a\": \"b\"}), { :a => :b }.to_json assert_equal %({\"a\": \"b\"}), { :a => :b }.to_json
assert_equal %({\"a\": 1}), { 'a' => 1 }.to_json assert_equal %({\"a\": 1}), { 'a' => 1 }.to_json
assert_equal %({\"a\": [1, 2]}), { 'a' => [1,2] }.to_json assert_equal %({\"a\": [1, 2]}), { 'a' => [1,2] }.to_json
assert_equal %({1: 2}), { 1 => 2 }.to_json assert_equal %({"1": 2}), { 1 => 2 }.to_json
sorted_json = '{' + {:a => :b, :c => :d}.to_json[1..-2].split(', ').sort.join(', ') + '}' sorted_json = '{' + {:a => :b, :c => :d}.to_json[1..-2].split(', ').sort.join(', ') + '}'
assert_equal %({\"a\": \"b\", \"c\": \"d\"}), sorted_json assert_equal %({\"a\": \"b\", \"c\": \"d\"}), sorted_json
@ -80,7 +80,7 @@ class TestJSONEncoding < Test::Unit::TestCase
def test_hash_key_identifiers_are_always_quoted def test_hash_key_identifiers_are_always_quoted
values = {0 => 0, 1 => 1, :_ => :_, "$" => "$", "a" => "a", :A => :A, :A0 => :A0, "A0B" => "A0B"} values = {0 => 0, 1 => 1, :_ => :_, "$" => "$", "a" => "a", :A => :A, :A0 => :A0, "A0B" => "A0B"}
assert_equal %w( "$" "A" "A0" "A0B" "_" "a" 0 1 ), object_keys(values.to_json) assert_equal %w( "$" "A" "A0" "A0B" "_" "a" "0" "1" ).sort, object_keys(values.to_json)
end end
def test_hash_should_allow_key_filtering_with_only def test_hash_should_allow_key_filtering_with_only