0

JSON.stringify refuses to format object, it keeps everything on a single line. Does anyone know why it does not work?

<!DOCTYPE html>
<html>
  <head>  
    <script>

var obj = {
 "a" : "1547645674576457645",
 "b" : "2790780987908790879087908790879087098",
 "c" : "38907908709879087",
 "d" : "A very long sentance or text1",
 "e" : "A very long sentance or text2",
 "f" : "A very long sentance or text3"

};

// pretty format trick
var myj=JSON.stringify(obj, null, 4);
//var myj=JSON.stringify(obj);
document.write(myj);

</script>

  </head> 
  <body>
</body>
</html>​
hrhsii
  • 157
  • 1
  • 12

1 Answers1

2
var myj=JSON.stringify(obj, null, 4);

You are formatting it. That's what the third argument does.

document.write(myj);

Then you are outputting it as HTML.

Spaces and new lines collapse, by default, in HTML, so the formatting is lost by the way you are presenting the JSON.

Wrap it in a <pre> element (and consider using document.createTextNode / appendChild instead of document.write so that any < and & in the data don't have unfortunate side effects).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335