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>​

6
  • you need to pretty-print it; per Default it doesn't care about formattings Commented Apr 27, 2017 at 12:06
  • That is formatted. JSON is a string. It sounds like you want it beautified. Commented Apr 27, 2017 at 12:06
  • Your Answer is here stackoverflow.com/questions/4810841/… Commented Apr 27, 2017 at 12:06
  • stackoverflow.com/questions/4810841/… try this answer, it might help you out here Commented Apr 27, 2017 at 12:06
  • 1
    document.write('<pre>' + myj + '</' + 'pre>'); Commented Apr 27, 2017 at 12:08

1 Answer 1

3
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).

Sign up to request clarification or add additional context in comments.

1 Comment

document.write('<pre>' + myj + '</' + 'pre>'); Worked perfectly thanks for the quick response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.