Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get to_json to escape front slashes

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?

like image 787
marketer Avatar asked Jul 24 '11 21:07

marketer


People also ask

How do you escape the front slash?

Slashes. The forward slash character is used to denote the boundaries of the regular expression: ? The backslash character ( \ ) is the escaping character.

How do you escape a forward slash in JSON?

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"} .

How do you escape a slash in a string?

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: ?

How do you escape the front slash in Python?

Programming languages, such as Python, treat a backslash (\) as an escape character. For instance, \n represents a line feed, and \t represents a tab.


1 Answers

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). 
like image 122
Apurva Mayank Avatar answered Oct 18 '22 00:10

Apurva Mayank