In rails, if I call "</script>".to_json
, the result is "\"</script>\""
. Neither angle brackets or front slashes are escaped. Is there a way to get to_json to escape these?
This little erb snippet demonstrates the problem:
<%= javascript_tag do %>
var a = <%= raw("</script>".to_json) %>;
alert("hi");
<% end %>
This produces the following output:
<script type="text/javascript">
//<![CDATA[
var a = "</script>";
alert("hi");
//]]>
</script>
In this case, the script tag is closed prematurely. Anyone have a good solution?
Slashes. The forward slash character is used to denote the boundaries of the regular expression: ? The backslash character ( \ ) is the escaping character.
JSON escapes the forward slash, so a hash {a: "a/b/c"} is serialized as {"a":"a/b/c"} instead of {"a":"a/b/c"} .
In the platform, the backslash character ( \ ) is used to escape values within strings. The character following the escaping character is treated as a string literal. For example, the following value is used to represent a matching value of & only: ?
Programming languages, such as Python, treat a backslash (\) as an escape character. For instance, \n represents a line feed, and \t represents a tab.
The slashes can be removed by using JSON.parse().
First of all you need to extract the body from the response that you are getting.
response_body = response_you_get_after_request.body
then pass response as argument as following:-
filtered_response = JSON.parse(response_body).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With