Skip to content
This repository
Browse code

Properly decode \u escape sequences in JSON [#1100 state:resolved] [T…

…im Pope, Philip Hallstrom]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information...
commit 9b9b2937ce3bef3bca9d22821e76c40cc74fa689 1 parent 0464254
Tim Pope authored March 10, 2009 lifo committed March 10, 2009
23  activesupport/lib/active_support/json/decoding.rb
@@ -43,14 +43,31 @@ def convert_json_to_yaml(json) #:nodoc:
43 43
           end
44 44
 
45 45
           if marks.empty?
46  
-            json.gsub(/\\\//, '/')
  46
+            json.gsub(/\\([\\\/]|u[[:xdigit:]]{4})/) do
  47
+              ustr = $1
  48
+              if ustr.starts_with?('u')
  49
+                [ustr[1..-1].to_i(16)].pack("U")
  50
+              elsif ustr == '\\'
  51
+                '\\\\'
  52
+              else
  53
+                ustr
  54
+              end
  55
+            end
47 56
           else
48 57
             left_pos  = [-1].push(*marks)
49 58
             right_pos = marks << scanner.pos + scanner.rest_size
50 59
             output    = []
51 60
             left_pos.each_with_index do |left, i|
52  
-              scanner.pos = left.succ
53  
-              output << scanner.peek(right_pos[i] - scanner.pos + 1)
  61
+              output << json[left.succ..right_pos[i]].gsub(/\\([\\\/]|u[[:xdigit:]]{4})/) do
  62
+                ustr = $1
  63
+                if ustr.starts_with?('u')
  64
+                  [ustr[1..-1].to_i(16)].pack("U")
  65
+                elsif ustr == '\\'
  66
+                '\\\\'
  67
+                else
  68
+                  ustr
  69
+                end
  70
+              end
54 71
             end
55 72
             output = output * " "
56 73
             
4  activesupport/test/json/decoding_test.rb
@@ -28,7 +28,9 @@ class TestJSONDecoding < Test::Unit::TestCase
28 28
     %(null)  => nil,
29 29
     %(true)  => true,
30 30
     %(false) => false,
31  
-    %q("http:\/\/test.host\/posts\/1") => "http://test.host/posts/1"
  31
+    %q("http:\/\/test.host\/posts\/1") => "http://test.host/posts/1",
  32
+    %q("\u003cunicode\u0020escape\u003e") => "<unicode escape>",
  33
+    %q("\\\\u0020skip double backslashes") => "\\u0020skip double backslashes"
32 34
   }
33 35
   
34 36
   TESTS.each do |json, expected|

0 notes on commit 9b9b293

Please sign in to comment.
Something went wrong with that request. Please try again.