I have some json that I want to display in a web page. However, the pre tag is stripping out and honoring the breaks in the output?
How can I display some json as such and keep all the text as is?
NOTE: i don't have control over the syntax. that is what is coming into my service so I'm just taking it and injecting it in the html into a pre.
<div>
<pre>
{
"text:" "testing line breaks<br/>new line"
}
</pre>
</div>
Output:
{
"text:" "testing line breaks
new line"
}
Expected Output:
{
"text:" "testing line breaks<br/>new line"
}
What you basically need to do is escape the HTML. You can use any language that you're using to output the string, but here is an example using native JavaScript and also jQuery:
var data = { data: 'This is not a <br /> new line' }
// Doesn't escape HTML
$('#1').html(JSON.stringify(data) );
// Escapes
$('#2').text(JSON.stringify(data) );
// Escapes
document.getElementById("3").innerText = JSON.stringify(data);
// Doesn't escape
document.getElementById("4").innerHTML = JSON.stringify(data);
// Escapes
document.getElementById("5").innerHTML = JSON.stringify(data).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
Note: If you don't have access to the way this HTML is generated, you can still fix it with a little Javascript snippet:
// If you can't decode the HTML but you can add a little snippet
var el = document.getElementById("6"); el.innerText = el.innerHTML;
// Using jQuery
var $el = $('#7'); $el.text( $el.html() );
jsFiddle
Check out this FIDDLE
var data = {
"text": "testing line breaks<br/>new line"
};
document.getElementsByTagName("pre")[0].innerText = JSON.stringify(data, null, 2);
Two important things here.
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