Emoji and Rails JSON output issue
Posted on 18 Feb 2012
While working on API for the iOS-based device i noticed that text with emoji that comes from devices is being stored normally in database but when its being rendered as JSON format it gets broken.
>> JSON({:a => "\360\237\230\204"}.to_json)
=> {"a"=>"\357\230\204"}
The problem is related to the Rails internals and its JSON escaping process. After digging around internet i've found that there're few posts that explain the bug and also provide few solutions.
Solution
The issue gets fixed by placing the following content into config/initializers/active_support_encoding.rb
file:
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