Permalink
Browse files

add a more robust json_escape method

  • Loading branch information...
1 parent 8170b95 commit ea0969934da6ccddde717e3d6ba4bb6b12f01704 @dewski committed May 24, 2012
Showing with 21 additions and 4 deletions.
  1. +13 −4 lib/json_builder/extensions.rb
  2. +4 −0 test/member_test.rb
  3. +4 −0 test/value_test.rb
@@ -13,17 +13,26 @@ def to_builder
end
class String
+ JS_ESCAPE_MAP = {
+ '\\' => '\\\\',
+ '</' => '<\/',
+ "\r\n" => '\n',
+ "\n" => '\n',
+ "\r" => '\n',
+ '"' => '\\"',
+ "'" => "\\'"
+ }
+
def to_builder
%("#{json_escape}")
end
private
def json_escape
- self.gsub(/\n/, '\\n').
- gsub(/\r/, '\\r').
- gsub(/\t/, '\\t').
- gsub(/\f/, '\\f')
+ gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) { |match|
+ JS_ESCAPE_MAP[match]
+ }
end
end
View
@@ -39,6 +39,10 @@ def test_custom_class
assert_equal '"hello": "olleh"', member('hello', Dozer.new('hello')).to_s
end
+ def test_double_quoted_value
+ assert_equal '"hello": "\"Hello\" he said"', member('hello', '"Hello" he said').to_s
+ end
+
def test_without_key
assert_raises(JSONBuilder::MissingKeyError) { member(nil, true).to_s }
end
View
@@ -64,4 +64,8 @@ def test_hash_value
def test_custom_class
assert_equal '"olleh"', value(Dozer.new('hello'))
end
+
+ def test_double_quoted_value
+ assert_equal '"\"hello\""', value('"hello"')
+ end
end

0 comments on commit ea09699

Please sign in to comment.