W3jar
305 words
2 minutes

Pretty JSON Output in JavaScript

To pretty-print JSON in JavaScript, you can use JSON.stringify with additional parameters for formatting. Here’s a breakdown of how you can do it:

Basic Example#

const obj = {
    name: "Alice",
    age: 25,
    city: "Wonderland",
};

// Convert the object to a pretty-printed JSON string
const prettyJson = JSON.stringify(obj, null, 2);

console.log(prettyJson);

Explanation#

  • JSON.stringify(value, replacer, space):
    • value: The value to convert to JSON.
    • replacer: A function or array that can be used to filter or modify the values being stringified. If you don’t need to use this, you can set it to null.
    • space: A string or number used for indentation. If you use a number, it specifies the number of spaces to use for indentation. If you use a string, it is used as the indentation (e.g., '\t' for tabs).

In the example above:

  • null is passed as the replacer (meaning no filtering is done).
  • 2 specifies that the JSON should be indented with 2 spaces.

More Complex Example#

For a more complex object with nested structures:

const complexObj = {
    name: "Bob",
    age: 30,
    address: {
        street: "123 Main St",
        city: "Springfield",
        zip: "12345",
    },
    hobbies: ["reading", "biking", "coding"],
};

// Pretty-print JSON with indentation and custom spacing
const prettyJsonComplex = JSON.stringify(complexObj, null, 4);

console.log(prettyJsonComplex);

In this example, 4 spaces are used for indentation, resulting in a more readable format for deeply nested JSON structures.

Additional Considerations#

  • Error Handling: Always ensure that the value passed to JSON.stringify is serializable. Circular references or non-serializable data (e.g., functions) will cause an error.

  • Displaying in HTML: If you want to display pretty-printed JSON in a web page, you might want to escape it to prevent it from being interpreted as HTML:

    <pre id="jsonOutput"></pre>
    <script>
        const json = {
            /* your JSON data here */
        };
        document.getElementById("jsonOutput").textContent = JSON.stringify(
            json,
            null,
            2
        );
    </script>
    

Using textContent ensures that the JSON is displayed as plain text in the <pre> tag, preserving formatting and avoiding HTML injection issues.