Permalink
Browse files

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]
  • Loading branch information...
NZKoz committed Jan 16, 2009
1 parent a53ad5b commit 0bed5bdb213ea68e2f167ac4f61f698f37cf2d69
@@ -5,7 +5,7 @@ class Hash
# the hash keys. For example:
#
# { :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.
#
@@ -39,7 +39,7 @@ def to_json(options = {}) #:nodoc:
returning result = '{' do
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 * ', '
result << '}'
end
@@ -59,7 +59,7 @@ def test_hash_encoding
assert_equal %({\"a\": \"b\"}), { :a => :b }.to_json
assert_equal %({\"a\": 1}), { 'a' => 1 }.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(', ') + '}'
assert_equal %({\"a\": \"b\", \"c\": \"d\"}), sorted_json
@@ -80,7 +80,7 @@ def test_exception_raised_when_encoding_circular_reference
def test_hash_key_identifiers_are_always_quoted
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
def test_hash_should_allow_key_filtering_with_only

1 comment on commit 0bed5bd

@ghost

This comment has been minimized.

Show comment Hide comment
@ghost

ghost Jan 16, 2009

Great stuff, this was affecting a few of our customers on http://getexceptional.com with extra session data that wasn’t being serialized correctly with the exception payload.

Good news!

ghost commented on 0bed5bd Jan 16, 2009

Great stuff, this was affecting a few of our customers on http://getexceptional.com with extra session data that wasn’t being serialized correctly with the exception payload.

Good news!

Please sign in to comment.