Home > Web Front-end > JS Tutorial > How can I pretty-print JSON in JavaScript and add syntax highlighting?

How can I pretty-print JSON in JavaScript and add syntax highlighting?

Linda Hamilton
Release: 2024-12-19 22:34:11
Original
519 people have browsed it

How can I pretty-print JSON in JavaScript and add syntax highlighting?

Pretty-Printing JSON in JavaScript

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
Copy after login

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>';
  });
}
Copy after login

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(/&amp;/g, '&amp;amp;').replace(/</g, '&amp;lt;').replace(/>/g, '&amp;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));
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template