Pretty-Print Json Using JavaScript

pretty-print JSON using JavaScript

Pretty-printing is implemented natively in JSON.stringify(). The third argument enables pretty printing and sets the spacing to use:

var str = JSON.stringify(obj, null, 2); // spacing level = 2

If you need syntax highlighting, you might use some regex magic like so:

function syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}

See in action here: jsfiddle

Or a full snippet provided below:

function output(inp) {

document.body.appendChild(document.createElement('pre')).innerHTML = inp;

}

function syntaxHighlight(json) {

json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');

return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {

var cls = 'number';

if (/^"/.test(match)) {

if (/:$/.test(match)) {

cls = 'key';

} else {

cls = 'string';

}

} else if (/true|false/.test(match)) {

cls = 'boolean';

} else if (/null/.test(match)) {

cls = 'null';

}

return '<span class="' + cls + '">' + match + '</span>';

});

}

var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]};

var str = JSON.stringify(obj, undefined, 4);

output(str);

output(syntaxHighlight(str));
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }

.string { color: green; }

.number { color: darkorange; }

.boolean { color: blue; }

.null { color: magenta; }

.key { color: red; }

JSON.stringify output to div in pretty print way

Please use a <pre> tag

demo : http://jsfiddle.net/K83cK/

var data = {

"data": {

"x": "1",

"y": "1",

"url": "http://url.com"

},

"event": "start",

"show": 1,

"id": 50

}

document.getElementById("json").textContent = JSON.stringify(data, undefined, 2);
<pre id="json"></pre>

How can I pretty-print JSON using node.js?

JSON.stringify's third parameter defines white-space insertion for pretty-printing. It can be a string or a number (number of spaces). Node can write to your filesystem with fs. Example:

var fs = require('fs');

fs.writeFile('test.json', JSON.stringify({ a:1, b:2, c:3 }, null, 4));
/* test.json:
{
"a": 1,
"b": 2,
"c": 3,
}
*/

See the JSON.stringify() docs at MDN, Node fs docs

How can I beautify JSON programmatically?

Programmatic formatting solution:

The JSON.stringify method supported by many modern browsers (including IE8) can output a beautified JSON string:

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4); // stringify with 4 spaces at each level
Demo: http://jsfiddle.net/AndyE/HZPVL/

This method is also included with json2.js, for supporting older browsers.

Manual formatting solution

If you don't need to do it programmatically, Try JSON Lint. Not only will it prettify your JSON, it will validate it at the same time.

pretty print JSON in td tags

Use both json.stringify() and <pre> tags. Aslong as you don't put your json in a <pre> block, it will be parsed as text by the HTML parser. If you put it inside the <pre> tags, it will be recognized as code.

var json = {"glossary":{"title":"example glossary","GlossDiv":{"title":"S","GlossList":{"GlossEntry":{"ID":"SGML","SortAs":"SGML","GlossTerm":"Standard Generalized Markup Language","Acronym":"SGML","Abbrev":"ISO 8879:1986","GlossDef":{"para":"A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso":["GML","XML"]},"GlossSee":"markup"}}}}};

$("table tr td pre").html(JSON.stringify(json, undefined, 2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>

<tr>

<td>

<pre>

</pre>

<td>

</tr>

</table>

Javascript: How to generate formatted easy-to-read JSON straight from an object?

JSON.stringify takes more optional arguments.

Try:

 JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab

From:

How can I beautify JSON programmatically?

Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre> tag to get newlines to show.

How can I pretty print keys and values of a JavaScript object on web page

Us Object.entries and map to format the data how you want to display it.

let dict = {
term1: "definition 1",
term2: "definition 2",
term3: "definition 3",
term4: "definition 4"
}

const str = Object.entries(dict).map(([key, value]) => `${key}: ${value}`).join("<br/>");

document.getElementById("out").innerHTML = str;
<div id="out"></div>


Related Topics



Leave a reply



Submit