How to prettyprint a JSON file?

6    Asked by JackGREEN in Python , Asked on Apr 29, 2025

How can I pretty-print a JSON file? Pretty-printing a JSON file involves formatting the content to make it more readable by adding indentation and line breaks. This can be easily done using built-in functions in most programming languages, such as JSON.stringify() in JavaScript or json.dumps() in Python.

Answered by Mayank

To pretty-print a JSON file, we essentially aim to format the JSON data so that it is easy to read and understand. This process adds indentation and line breaks to the raw JSON structure, making it more visually organized.

Here’s how you can pretty-print a JSON file in different programming languages:

In [removed]

Use the JSON.stringify() method with additional arguments for indentation.

const jsonObject = { name: "John", age: 30, city: "New York" };
const prettyJson = JSON.stringify(jsonObject, null, 2); // '2' indicates 2 spaces for indentation
console.log(prettyJson);

Explanation:

  • The null is for a replacer function (unused here).
  • The 2 specifies the number of spaces to use for indentation.

In Python:

You can use the json.dumps() method with indent to pretty-print JSON data.

import json
data = {"name": "John", "age": 30, "city": "New York"}
pretty_json = json.dumps(data, indent=2)
print(pretty_json)

Explanation:

  • The indent parameter defines how many spaces to use for each level of indentation.
  • This method returns a string, making it easy to output or write to a file.

In Command-Line (Linux/Unix):

You can also use tools like jq to pretty-print JSON in the terminal:

  cat file.json | jq .

Why Pretty-Print JSON?

  • Improved Readability: Easier for humans to read and debug.
  • Organized Structure: Helps identify nested elements and their relationships.

Pretty-printing is essential when dealing with complex data structures or when JSON needs to be logged or presented in a human-readable format.



Your Answer

Interviews

Parent Categories