Home >Web Front-end >JS Tutorial >How Can I Pretty-Print JSON with Syntax Highlighting?
Transforming JSON into a more visually appealing and human-readable format can be achieved through pretty-printing. This method enhances readability by utilizing indentation and whitespace, and may even include colors or font styles.
JSON.stringify() natively incorporates pretty-printing capabilities. By specifying a third argument, you can enable pretty-printing and define the indentation level.
var str = JSON.stringify(obj, null, 2); // sets spacing to 2
To incorporate syntax highlighting into your pretty-printed JSON, you can harness the power of regular expressions.
function syntaxHighlight(json) { // ... regular expression magic goes here ... }
Below is a complete example that demonstrates syntax highlighting alongside pretty-printing:
function output(inp) { document.body.appendChild(document.createElement('pre')).innerHTML = inp; } function syntaxHighlight(json) { // ... regular expression magic goes here ... } var obj = { ... }; var str = JSON.stringify(obj, undefined, 4); output(str); output(syntaxHighlight(str));
This example showcases pretty-printing with indentation and syntax highlighting in action.
The above is the detailed content of How Can I Pretty-Print JSON with Syntax Highlighting?. For more information, please follow other related articles on the PHP Chinese website!