Home >Web Front-end >JS Tutorial >How to Pretty-Print JSON in JavaScript?
Pretty-Print JSON Using JavaScript
Converting JSON data into a human-readable format is crucial for debugging and understanding its structure. In JavaScript, "pretty-printing" JSON is natively supported through the JSON.stringify() method.
Native Pretty-Printing
The JSON.stringify() function takes three arguments: the JSON object to convert, a replacer function (optional), and the spacing level (optional). To specify spacing, pass a positive integer as the third argument. For example:
var obj = { foo: 'bar', baz: [1, 2, 3] }; var json = JSON.stringify(obj, null, 2);
This will produce:
"{ "foo": "bar", "baz": [ 1, 2, 3 ] }"
Syntax Highlighting
For more visual clarity, you can use regular expressions to apply syntax highlighting to the JSON string. For example:
function syntaxHighlight(json) { // Escape HTML characters json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); // Highlight different types using span tags 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 will replace key elements with different colors and styles to make the JSON structure more readable.
Example
Here's an example that combines native pretty-printing and syntax highlighting:
// Pretty-print the JSON object var json = JSON.stringify(obj, null, 2); // Highlight the JSON string var highlighted = syntaxHighlight(json); // Display the highlighted JSON string in the browser console console.log(highlighted);
The above is the detailed content of How to Pretty-Print JSON in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!