Skip to content

Instantly share code, notes, and snippets.

@garrytan
Created October 15, 2009 05:22
Show Gist options
  • Select an option

  • Save garrytan/210704 to your computer and use it in GitHub Desktop.

Select an option

Save garrytan/210704 to your computer and use it in GitHub Desktop.
# this is needed so that we can still access the original ActiveSupport version of JSON encoding
# JSON gem is faster but does not support automatic unicode conversion for < and >, which can cause
# problems for </script> in JSON output (browser interprets as exiting the script area, and results in XSS exploit)
#
# e.g. EscapableJsonString.new('<no_xss>').to_json
# => "\u003Cno_xss\u003E"
#
class EscapableJsonString < String
def to_json(options = nil) #:nodoc:
json = '"' + gsub(ActiveSupport::JSON::Encoding.escape_regex) { |s|
ActiveSupport::JSON::Encoding::ESCAPED_CHARS[s]
}
json.force_encoding('ascii-8bit') if respond_to?(:force_encoding)
json.gsub(/([\xC0-\xDF][\x80-\xBF]|
[\xE0-\xEF][\x80-\xBF]{2}|
[\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s|
s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/, '\\\\u\&')
} + '"'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment