eclipseIzHere eclipseIzHere - 2 months ago 19
Javascript Question

Formatting Object Output

I have a object:

var computer={
"Home":{

},
"Desktop":{

},
"Documents":{

},
"Downloads":{

},
"Library":{

},
"Movies":{

},
"Music":{

},
"Pictures":{

},
"Library":{

},
"Downloads":{

},
"Files":{

},
"Devices":{

},
"USB":{

},
"Hard_Drive":{

}
}


and i have a for in loop that outputs it into html.

var exp=JSON.stringify(computer);
$("#targetDiv").append('<p class="text">'+exp+'</p>');


but the output is this:

{"Home":{},"Desktop":{},"Documents":{},"Downloads":{},"Library":{},"Movies":{},"Music":{},"Pictures":{},"Files":{},"Devices":{},"USB":{},"Hard_Drive":{}}


how do i format it so it would look like this?

{
"Home":{},
"Desktop":{},
"Documents":{},
"Downloads":{},
"Library":{},
"Movies":{},
"Music":{},
"Pictures":{},
"Files":{},
"Devices":{},
"USB":{},
"Hard_Drive":{}
}


I think i need a loop that loops through the output and whenever there is a comma or a }, it puts a break html tag. but i have no idea how to do that. thanks in advance.

Answer

As Tushar mentioned, one way is to put the output of JSON.stringify() inside a <pre>.

var computer={
    "Home":{},
    "Desktop":{},
    "Documents":{},
    "Downloads":{},
    "Library":{},
    "Movies":{},
    "Music":{},
    "Pictures":{},
    "Library":{},
    "Downloads":{},
    "Files":{},
    "Devices":{},
    "USB":{},
    "Hard_Drive":{}
}

$("#targetDiv").append('<pre>' + JSON.stringify(computer,null,1) + '</pre>');    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="targetDiv"></div>