From 06f7e594bdffe9b647d73ec1a1e257ab41344070 Mon Sep 17 00:00:00 2001 From: Maxime RETY Date: Mon, 14 Jun 2010 16:05:49 +0200 Subject: [PATCH] Fix JSON decoding of newline character with Yaml backend [#3479 state:resolved] --- .../lib/active_support/json/backends/yaml.rb | 8 ++++++-- activesupport/test/json/decoding_test.rb | 6 +++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/activesupport/lib/active_support/json/backends/yaml.rb b/activesupport/lib/active_support/json/backends/yaml.rb index 215b3d6..7e4b7d0 100644 --- a/activesupport/lib/active_support/json/backends/yaml.rb +++ b/activesupport/lib/active_support/json/backends/yaml.rb @@ -47,7 +47,9 @@ module ActiveSupport json.gsub(/\\([\\\/]|u[[:xdigit:]]{4})/) do ustr = $1 if ustr.start_with?('u') - [ustr[1..-1].to_i(16)].pack("U") + char = [ustr[1..-1].to_i(16)].pack("U") + # "\n" needs extra escaping due to yaml formatting + char == "\n" ? "\\n" : char elsif ustr == '\\' '\\\\' else @@ -68,7 +70,9 @@ module ActiveSupport chunk.gsub!(/\\([\\\/]|u[[:xdigit:]]{4})/) do ustr = $1 if ustr.start_with?('u') - [ustr[1..-1].to_i(16)].pack("U") + char = [ustr[1..-1].to_i(16)].pack("U") + # "\n" needs extra escaping due to yaml formatting + char == "\n" ? "\\n" : char elsif ustr == '\\' '\\\\' else diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index d2e3efa..d2b6946 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -41,7 +41,11 @@ class TestJSONDecoding < ActiveSupport::TestCase [{'d' => Date.new(1970, 1, 1), 's' => ' escape'},{'d' => Date.new(1970, 1, 1), 's' => ' escape'}], %q([{"d":"1970-01-01","s":"http:\/\/example.com"},{"d":"1970-01-01","s":"http:\/\/example.com"}]) => [{'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'}, - {'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'}] + {'d' => Date.new(1970, 1, 1), 's' => 'http://example.com'}], + # tests escaping of "\n" char with Yaml backend + %q("\n") => "\n", + %q("\u000a") => "\n", + %q({"a":"Line1\u000aLine2"}) => {"a"=>"Line1\nLine2"} } # load the default JSON backend -- 1.6.1.3