JSON encoding wrongly escaped (Rails 3, Ruby 1.9.2)

后端 未结 7 1470
醉梦人生
醉梦人生 2020-12-01 08:14

In my controller, the following works (prints \"oké\")

puts obj.inspect

But this doesn\'t (renders \"ok\\u00e9\")

render :j         


        
7条回答
  •  一向
    一向 (楼主)
    2020-12-01 08:52

    You can prevent it by monkey patching the method mentioned by muu is too short. Put the following into config/initializers/patches.rb (or similar file used for patching stuff) and restart your rails process for the change to take affect.

    module ActiveSupport::JSON::Encoding
      class << self
        def escape(string)
          if string.respond_to?(:force_encoding)
            string = string.encode(::Encoding::UTF_8, :undef => :replace).force_encoding(::Encoding::BINARY)
          end
          json = string.gsub(escape_regex) { |s| ESCAPED_CHARS[s] }
          json = %("#{json}")
          json.force_encoding(::Encoding::UTF_8) if json.respond_to?(:force_encoding)
          json
        end
      end
    end
    

    Be adviced that there's no guarantee that the patch will work with future versions of ActiveSupport. The version used when writing this post is 3.1.3.

提交回复
热议问题