From f4207b0fcd859797ff421d407ffcccf176c4ab87 Mon Sep 17 00:00:00 2001 From: Noah Davis Date: Mon, 12 Jan 2009 21:10:25 -0500 Subject: [PATCH] all JSON hash keys need to be double quoted --- .../lib/active_support/json/encoders/hash.rb | 19 ++++++++++++++++++- activesupport/test/json/encoding_test.rb | 4 ++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/activesupport/lib/active_support/json/encoders/hash.rb b/activesupport/lib/active_support/json/encoders/hash.rb index b9bdd55..b02da3f 100644 --- a/activesupport/lib/active_support/json/encoders/hash.rb +++ b/activesupport/lib/active_support/json/encoders/hash.rb @@ -1,3 +1,19 @@ +module ActiveSupport + module JSON + module Encoding + + def self.ensure_double_quoted(str) + if str && str.length > 1 && str.starts_with?("\"") && str.ends_with?("\"") + str + else + "\"#{str}\"" + end + end + + end + end +end + class Hash # Returns a JSON string representing the hash. # @@ -39,9 +55,10 @@ class Hash returning result = '{' do result << hash_keys.map do |key| - "#{ActiveSupport::JSON.encode(key)}: #{ActiveSupport::JSON.encode(self[key], options)}" + "#{ActiveSupport::JSON::Encoding.ensure_double_quoted(ActiveSupport::JSON.encode(key))}: #{ActiveSupport::JSON.encode(self[key], options)}" end * ', ' result << '}' end end + end diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index 8ed21cc..2c5b4d0 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -59,7 +59,7 @@ class TestJSONEncoding < Test::Unit::TestCase 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 @@ class TestJSONEncoding < Test::Unit::TestCase 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.6.0.2