JSON
prettyprint
programming
data formatting
code tutorial

How to prettyprint a JSON file?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

JSON (JavaScript Object Notation) is a lightweight data interchange format that's easy for humans to read and write, and easy for machines to parse and generate. When working with JSON files, especially large ones, they can become difficult to read when printed in their compact form. Pretty-printing JSON involves formatting the data with indentation and newlines for improved readability. Here’s how you can pretty-print a JSON file using different programming languages and tools.

Techniques to Pretty-Print JSON

Using Command Line Tools

1. Python

Python’s json module provides built-in support for pretty-printing. Below is a Python script to pretty-print a JSON file.

python
1import json
2
3def pretty_print_json(file_path):
4    with open(file_path, 'r') as file:
5        data = json.load(file)
6    print(json.dumps(data, indent=4))
7
8pretty_print_json('data.json')

In this script:

  • json.load(file) is used to parse the JSON file.
  • json.dumps() with indent=4 specifies the number of spaces for indentation.

2. jq (Command-line JSON processor)

jq is a powerful command-line tool for processing JSON data.

bash
jq '.' data.json

Running the command above will print the contents of data.json with default formatting. Adjust the command as needed to output with specific indent levels.

Using Web Tools

There are various online tools available that allow users to upload a JSON file and receive a pretty-printed version. These tools typically offer additional features like error checking and conversion to different formats.

Pretty-Printing JSON in Different Programming Languages

1. JavaScript (Node.js)

JavaScript, being the language JSON is derived from, easily handles JSON data using built-in methods.

javascript
1const fs = require('fs');
2
3fs.readFile('data.json', 'utf8', (err, data) => {
4    if (err) throw err;
5    const jsonData = JSON.parse(data);
6    console.log(JSON.stringify(jsonData, null, 4));
7});
  • JSON.parse(data) parses the JSON string into a JavaScript object.
  • JSON.stringify(jsonData, null, 4) converts the object back to a JSON string with a 4-space indentation.

2. Java

For Java, you can make use of libraries like Jackson or Gson to pretty-print JSON.

Using Jackson:

java
1import com.fasterxml.jackson.databind.ObjectMapper;
2import com.fasterxml.jackson.databind.ObjectWriter;
3
4public class PrettyPrintJSON {
5    public static void main(String[] args) throws Exception {
6        ObjectMapper mapper = new ObjectMapper();
7        Object json = mapper.readValue(new File("data.json"), Object.class);
8        ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
9        System.out.println(writer.writeValueAsString(json));
10    }
11}

Using Gson:

java
1import com.google.gson.Gson;
2import com.google.gson.GsonBuilder;
3
4public class PrettyPrintJsonGson {
5    public static void main(String[] args) throws Exception {
6        Gson gson = new GsonBuilder().setPrettyPrinting().create();
7        JsonReader reader = new JsonReader(new FileReader("data.json"));
8        Object jsonObject = gson.fromJson(reader, Object.class);
9        String prettyJson = gson.toJson(jsonObject);
10        System.out.println(prettyJson);
11    }
12}

Summary Table

Below is a summary table of different ways to pretty-print JSON across various tools and languages:

Method/ToolLanguage/ToolCommand/Syntax
Python scriptPythonjson.dumps(data, indent=4)
jq toolTerminaljq '.' data.json
JavaScript (Node.js)JavaScriptJSON.stringify(obj, null, 4)
Jackson LibraryJavawriter.writeValueAsString(json)
Gson LibraryJavagson.toJson(jsonObject)

Additional Considerations

  • Whitespace Sensitivity: JSON itself is not whitespace-sensitive and all pretty-printing does not affect its parseability.
  • Security: When pretty-printing JSON, be cautious with JSON data from untrusted sources as parsing and serializing may expose your application to injection risks if not properly handled.
  • Performance: Large JSON files may take longer to pretty-print due to the additional processing required for indentation and sorting keys.

Incorporating pretty-printing into your workflow can vastly improve the process of debugging and analyzing JSON data, making it a valuable skill for developers working with APIs and data interchange formats.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions