Skip to content

Commit

Permalink
Properly quote json keys.
Browse files Browse the repository at this point in the history
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 0bed5bd
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 4 deletions.
4 changes: 2 additions & 2 deletions activesupport/lib/active_support/json/encoders/hash.rb
Expand Up @@ -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.
#
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions activesupport/test/json/encoding_test.rb
Expand Up @@ -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
Expand All @@ -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
Expand Down

1 comment on commit 0bed5bd

@intercom
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.