Home >Web Front-end >JS Tutorial >How Can I Pretty-Print JSON with Syntax Highlighting?

How Can I Pretty-Print JSON with Syntax Highlighting?

DDD
DDDOriginal
2024-12-15 18:19:14531browse

How Can I Pretty-Print JSON with Syntax Highlighting?

Displaying JSON in a Human-Readable Format: Pretty-printing

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.

Native JSON.stringify() Method

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

Syntax Highlighting with Regular Expressions

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 ...
}

Full-Fledged Example

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn