Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display breaks in pre tag via formatted json?

Tags:

json

html

css

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"
}
like image 546
genxgeek Avatar asked Dec 08 '22 09:12

genxgeek


2 Answers

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,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');

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

like image 93
Alain Jacomet Forte Avatar answered Dec 11 '22 11:12

Alain Jacomet Forte


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.

  1. element.innerText will not honor the HTML br tag
  2. JSON.stringify's 3rd argument takes number of spaces to use when pretty printing it
like image 26
cbayram Avatar answered Dec 11 '22 12:12

cbayram