Reputation: 3184
I'm attempting to output some formatted JSON that I'm generating, but it doesn't seem to be working. I'd like to have each JSON object all tabbed and spaced correctly to be very readable. What am I doing wrong here?
var arr = new Array(20).fill().map(function() {
var first = chance["first"]({gender: "male"});
var last = chance["last"]();
var company = "DinnerCall";
var city = chance["city"]();
var state = chance["state"]();
var address = chance["address"]();
return {
first: first,
last: last,
email: first.toLowerCase() + "." + last.toLowerCase() + "@" + company.toLowerCase() + ".com",
company: company,
address: address,
state: chance["state"](),
};
});
var jsonPretty = JSON.stringify({users: arr}, null, '\t');
$("body").text(jsonPretty);
https://jsfiddle.net/La5qstdd/5/
Upvotes: 0
Views: 45
Reputation: 2327
Browsers by default escape spaces in HTML.
Using a <pre>
tag can help.
Instead of trying to insert the text into <body>
, try changing your html to have a <pre>
tag, or a "preformatted text" section.
var json = {
a: 'Hello',
b: 'World',
c: {
d: 'Hello',
e: 'World'
}
};
var jsonPretty = JSON.stringify(json, null, 2);
$(".json-content")
.text(jsonPretty);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<pre class="json-content">
</pre>
</body>
Upvotes: 1
Reputation: 142
What you are doing is actually working. The problem is that html does not care about the whitespaces you are adding unless you tell it to do so. What you need is the <pre>...</pre>
tag. This will make html recognize your whitespaes and show your JSON accordingly. To do this, you could for example change your last line from $("body").text(jsonPretty);
to $("body").html("<pre>" + jsonPretty + "</pre>");
. This might not be the cleanest solution, but it works and should make your problem clear.
Upvotes: 0