Displaying JSON in a human-readable format is essential for comprehending and debugging data. In JavaScript, this is achieved through the native JSON.stringify() function.
Native Pretty-Printing:
The third argument of JSON.stringify() enables pretty-printing and specifies the indentation level. For instance:
var str = JSON.stringify(obj, null, 2); // spacing level = 2
This will output JSON with 2 spaces of indentation, making it easier to read.
Syntax Highlighting:
For more elaborate formatting, you can use regular expressions to highlight different elements within the JSON string.
function syntaxHighlight(json) { 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>'; }); }
This function replaces certain patterns with HTML tags to apply styles such as color to different JSON elements.
Full Code Snippet:
Here's a comprehensive example:
function output(inp) { document.body.appendChild(document.createElement('pre')).innerHTML = inp; } function syntaxHighlight(json) { return json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); } 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));
This script parses a JSON object, pretty-prints it, and displays it along with syntax-highlighted JSON.
The above is the detailed content of How can I pretty-print JSON in JavaScript and add syntax highlighting?. For more information, please follow other related articles on the PHP Chinese website!