class method self.json_escape

Ruby on Rails 3.2.22.5

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

self.json_escape(s)

A utility method for escaping HTML entities in JSON strings using \uXXXX JavaScript escape sequences for string literals:

json_escape("is a > 0 & a < 10?")
# => is a \u003E 0 \u0026 a \u003C 10?

Note that after this operation is performed the output is not valid JSON. In particular double quotes are removed:

json_escape('{"name":"john","created_at":"2010-04-28T01:39:31Z","id":1}')
# => {name:john,created_at:2010-04-28T01:39:31Z,id:1}

This method is also aliased as j, and available as a helper in Rails templates:

<%=j @person.to_json %>

Parameters

s req
Source
# File activesupport/lib/active_support/core_ext/string/output_safety.rb, line 64
    def json_escape(s)
      result = s.to_s.gsub(/[&"><]/) { |special| JSON_ESCAPE[special] }
      s.html_safe? ? result.html_safe : result
    end

Defined in activesupport/lib/active_support/core_ext/string/output_safety.rb line 64 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ERB::Util

Type at least 2 characters to search.

↑↓ navigate · open · esc close