Reputation: 1
I am using json.stringify()
function to print my result in proper my div output1.
$("div#output1").html(JSON.stringify(response))
The result is:
" {\n \"prediction\": \"Positive\",\n \"confidence_score\": {\n \"Positive\": \"56.49\",\n \"Negative\": \"43.51\"\n }\n}\n\r\n"
How can I remove these \n \ \r
?
Upvotes: 0
Views: 597
Reputation: 11597
Use text()
instead of html()
:
$("div#output1").text(JSON.stringify(response));
This will create a proper text type node in the DOM and not escape to HTML.
If the problem persists, it may be server-side. In that case look at the HTTP response to see what you actually get from the server.
On chrome, press F12 to open the dev tools, go to network, reload the page with F5 and fire the AJAX request again. At that point you'll see the HTTP request/response entry. Click it, and inspect the response sheet, there you'll see the raw ASCII data served by the server. If that's still escaped then the problem is server-side.
In PHP use var_dump()
to output that string directly onto the page (without AJAX) and look at it. It may be already escaped in the database. In that case you'll have to unescape it somewhere along the response pipeline. The easiest thing will be to unescape it directly in JS on the client-side. That won't require you to change the rest of the application (namely, the input forms). Keeping escaped strings in the database is a good idea, in fact.
You may want to have <pre>
tags for the output of the text node:
<pre id="output1"></pre>
Upvotes: 6
Reputation: 3568
I am not sure how you get this strange output.
As you can see in the snippets, the json has no \n
and friends.
I used a pre
instead of div
so if \n
was there it would create a new line.
var response = {
"prediction": "Positive",
"confidence_score": {
"Positive": "56.49",
"Negative": "43.51"
}
};
$("pre#output1").html(JSON.stringify(response));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="output1"></pre>
Still, what you can do on your string is to replace the values... Something like this:
var output = " {\n \"prediction\": \"Positive\",\n \"confidence_score\": {\n \"Positive\": \"56.49\",\n \"Negative\": \"43.51\"\n }\n}\n\r\n";
$('#original').html(output);
$('#output1').html(output.replace(/\r|\n|\"/g, ''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
original:
<pre id="original"></pre>
output:
<pre id="output1"></pre>
Upvotes: 1