Home > Web Front-end > JS Tutorial > How to Pretty-Print JSON in JavaScript?

How to Pretty-Print JSON in JavaScript?

Patricia Arquette
Release: 2024-12-14 04:35:09
Original
285 people have browsed it

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

This will produce:

"{
  "foo": "bar",
  "baz": [
    1,
    2,
    3
  ]
}"
Copy after login

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, '&amp;').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>`;
  });
}
Copy after login

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

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!

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