3 Best Ways to Prettify JSON in Linux

TL;DR

To prettify JSON in the Linux command line, you try these three methods:

  1. Use the jq command to prettify JSON in Linux cat filename.json | jq '.' -C. And if you want to save the output in a separate file, you can execute cat filename.json | jq '.'> outputfilename.json.
  2. Use the python3 command python3 -m json.tool filename.json to display the prettified output of your JSON file in the Terminal.
  3. You can also pretty print your JSON file with the json_xs command and save the result to a new file using cat filename.json | json_xs > structured.json.

To more efficiently prettify JSON in Linux, follow these best practices like using a consistent format, syntax highlighting, and indentation style. Moreover, you should minimize unnecessary whitespace, verify output, make backups, avoid tabs, and validate JSON. Troubleshooting common errors like invalid JSON, incorrect command syntax, and missing dependencies also helps in JSON prettification. You can also use third-party online tools like jsonformatter.org, jsoneditoronline.org, jsonlint.com, and Online JSON Viewer to quickly prettify JSON code.

For a detailed, step-by-step tutorial on making JSON more readable in Linux, don’t miss the full article below.

JSON (JavaScript Object Notation) is a popular lightweight data format for exchanging information between systems. Despite its ease of use, large JSON files can become challenging to read, making it difficult for developers to work with them. One solution is to prettify JSON by adding indentation, spacing, and line breaks. This enhances the readability and understanding of the file. In this article, I will explore the three ways to prettify JSON code using the Linux command line and third-party online tools.

How to Prettify JSON in Linux in 3 Easy Ways

There are three ways to prettify JSON in the Linux command line. That includes the use of jq, python3, and json_xs commands. To learn more, let’s have a closer look at each of them here:

1. jq Command to Prettify JSON

The basic method to prettify JSON in Linux is to use the jq command-line utility. It is a lightweight, flexible command-line JSON processor for formatting, querying, and manipulating JSON data. Here’s how you can use jq to prettify JSON, follow these steps:

  1. Install jq if it’s not already installed using the package manager for your distribution. For example, if you are using Ubuntu or Debian, you can install it using the following command:
sudo apt-get install jq
  1. Type y and press Enter to continue with the solution.
sudo apt get install jq
  1. After that, head to the directory where your JSON file is located. Note down the directory path and verify whether it has proper formatting or not.
note down the directory path
  1. Next, open the JSON file in the Linux command line. Navigate to the directory where your JSON file is located using the cd command.
json file is located using the cd command
  1. Pipe the JSON data to the jq command, and use the -C option to enable color output in the Terminal app with syntax highlighting:
cat filename.json | jq '.' -C
  1. Once you execute the command, you’ll get the following output:
pipe the json data to jq command prettify json in the linux
  1. If you need this output in a separate JSON file, use the > operator with the jq command to redirect the output to a new file. Here’s the command to execute in the Terminal window:
cat filename.json | jq '.' > outputfilename.json
  1. As you execute the command and no error pops up, it means that the command is executed and the JSON file output has been created in the current directory.
operator with the jq command to redirect the output
  1. Head to the directory path where you have created the file to check the output file.
created the file to check the output file
  1. Click the file to view the formatted output.
file to view the formatted output prettify json in the linux
  1. To validate the newly created JSON file, you may need to install JSON package with the following command:
sudo apt install python3-demjson
sudo apt install python3 demjson
  1. Then, you can use the jsonlint tool to validate the JSON syntax:
jsonlint outputfilename.json
jsonlint tool to validate the json syntax
  1. Here’s an example of JSON files before and after prettification using the jq command:

Before Prettification:

files before and after prettify json in the linux

After Prettification:

files before and after prettify json

2. python3 Command to Pretty Print JSON Files

If you want to make your JSON files more readable and user-friendly, you can pretty-print them using python3. Here’s how you can do it:

  1. In the Terminal app, navigate to the directory containing the JSON file using the cd command.
navigate to the directory containing the json file
  1. Run the following command, replacing File.json with the name of your JSON file:
python3 -m json.tool filename.json 
  1. The JSON file will be pretty-printed in the Terminal output.
python3 m json prettify json in the linux

3. json_xs Command to Pretty Print JSON Files

The json_xs command is a powerful tool that can be used to pretty print JSON files in the terminal and even save the result to a new file. Here are the steps to follow:

  1. Launch the Terminal app and use the cd command to navigate to the directory containing the JSON file.
use the cd command to navigate
  1. Run the following command, replacing filename.json with the name of your JSON file and structured.json with the desired output filename:
cat filename.json json_xs > structured.json

Note: You may need to execute sudo apt install libjson-xs-perl to run the above-mentioned command.

sudo apt install libjson xs perl
  1. This command will pretty print the JSON file and save the result to a new file called filename_structured.json.
pretty print the json file
  1. Once you open these files, you’ll notice that the original file remains unaltered while the newly created file is well-structured and formatted. Here is the output:

Before Prettification:

original file remains unaltered

After Prettification:

newly created file is well structured

Top 4 Third-Party Tools to Prettify JSON Code

When working with small amounts of data, online tools can be a great option for prettifying JSON files. These tools provide a user-friendly interface for prettifying JSON. Some popular tools are as follows:

1. jsonformatter.org

This tool allows you to paste your JSON code directly into the tool and click the Format button to prettify the code. Additionally, it offers options to compress or minify the code, making it versatile for working with JSON files.

jsonformatter org paste your json code

2. jsoneditoronline.org

This tool provides a user-friendly interface for viewing, searching, and editing JSON files. It offers a tree view of the JSON structure and allows you to collapse and expand nodes as needed. To format your JSON code, simply click the Transform button, and you’ll see the formatted output on the right side of the screen.

    jsoneditoronline org user friendly interface

    3. jsonlint.com

    This tool provides a simple interface for validating and formatting JSON code. You can paste your code directly into the tool, and it will provide information on any errors or issues with the code. This can be a useful tool for debugging small parts of codes and ensuring that your JSON files are properly formatted.

      jsonlint com simple interface for validating and formatting

      4. Online JSON Viewer

      This tool by BeautifyTools allows you to upload from a URL or paste JSON data and format. It has options for indentation, sorting, and collapsing or expanding nested elements. In the viewer mode, you can see the value of each variable in the table view.

      online json viewer beautifytools allows you to upload from url

      6 Troubleshooting Tips When Prettifying JSON

      Here are some common errors you may encounter when prettifying JSON in the Linux command line and how to troubleshoot them:

      • Incorrect formatting: If the output formatting is not as expected, check the command options and make sure you are using the appropriate flags for the desired output. For instance, if you want to indent with four spaces instead of two, you may need to use a different flag or option like --indent 4. Your command should look like this: jq '.' data.json --indent 4. Once executed, it will prettify your JSON data file with four indentation spaces.
      • 🔎 File not found: If you are attempting to prettify a JSON file and receive an error indicating that the file cannot be found, double-check the file path and make sure you are using the correct path and file name. You can use the ls command to list the files in a directory and verify the file’s existence. Alternatively, you can search for that particular file by using the find and file.
      • 🔒 Permissions issues: To troubleshoot and resolve a “permission denied” error when attempting to prettify a JSON file, you should check the file permissions using the ls -l command to verify that you have the appropriate privileges to access or modify the file. If the file permissions do not allow you to read or write the file, you can use the chmod u+rw filename.json command to change the file permissions accordingly.
      • 📁 Large file size: Attempting to prettify a very large JSON file may result in performance issues or unexpected errors. In this case, consider splitting the file into smaller sections using split. For example, you can split a large JSON file into smaller chunks of 1000 lines each using the split -l 1000 largefile.json smaller-file-prefix command. Alternatively, you can prettify JSON data using cat and jq with the --compact-output option. The command should look like this: cat data.json | jq --compact-output '.'.
      • 🚫 Unsupported file types: To avoid errors when prettifying JSON data, make sure to use a prettifying command that supports the file type you are working with. You can usually find information about supported file types and formats in the command documentation or by using the --help option. If the file format is not supported, you can use certain tools and libraries to convert the file formats, such as jq, python-json.tool, and json_normalize in Python. For example, you can use the jq and csvjson commands to convert a CSV file to JSON format before prettifying. Your command should look like this: csvjson data.csv | jq '.'.
      • 🔣 Encoding issues: If you encounter encoding errors or issues when attempting to prettify a JSON file, check the file encoding and make sure the prettifying command supports it. You can use the file command to check the file encoding. If it is not supported, use the iconv command to convert the file to a different encoding format before attempting to prettify it. For example, use iconv -f utf-16 -t utf-8 data.json > newdata.json to convert a file from UTF-16 to UTF-8 encoding.

      8 Best Practices for Prettifying JSON in Linux Command Line

      Prettifying JSON can make it easier to read and understand, but some best practices should be followed to ensure that the output is clear and organized. Some best practices for prettifying JSON in the Linux command line include the following:

      • 🔧 Use Consistent Formatting: Consistency in formatting the JSON document, including indentation, spacing, and line breaks, makes the document easier to read and understand.
      • 🚀 Minimise Unnecessary Whitespace: Remove unnecessary whitespace from the JSON document, such as trailing spaces or extra blank lines. It makes the document more compact and easier to read. Use jq to remove unnecessary whitespace: jq . input.json > output.json
      • 🎨 Use Syntax Highlighting: Use a tool that supports syntax highlighting, such as jq or an online editor to make the JSON document more readable.
      • 🔍 Verify the Output: Always verify the output after prettifying the JSON to ensure that it is still valid JSON and that no data has been lost or corrupted.
      • 💾 Always Make a Backup: Before prettifying the JSON file, backup the original file to avoid data loss or corruption in case something goes wrong. Use cp to create a backup: cp input.json input.json.backup
      • 📏 Use Consistent Indentation Style: Consistent indentation style in the JSON file enhances readability and ensures uniformity.
      • 🚫 Avoid Using Tabs: Avoid using tabs for indentation, as they can cause issues when transferring files between different operating systems. Use spaces instead.
      • Validate your JSON: Use a tool like JSONLint to validate your JSON file before prettifying it. It ensures that the JSON file is valid and can be used without issues.

      Key Takeaways

      To improve JSON readability, make sure to prettify them using Linux command-line tools like jq, python3, and json_xs. Apart from these methods, you should follow the best practices for consistent formatting, removing unnecessary whitespace, and verifying output. Also, you may need to troubleshoot common issues, like invalid JSON or incorrect command syntax, for successful prettification. Third-party tools are also available for JSON formatting.

      In addition to JSON prettification, you should check out my detailed guide on using the echo command to make your code more readable. While you are at it, explore the efficient file-reading techniques and master regular expressions with the grep command to level up your Linux programming skills. Learning them will allow you to manipulate and process data in different Linux tasks efficiently. So, it’s definitely worth diving into these topics!

      Frequently Asked Questions

      JSON stands for JavaScript Object Notation, a lightweight and easy-to-read format for exchanging data between systems. It is popular because it is platform-independent, human-readable, and can be easily parsed by many programming languages.

      Does prettifying JSON change its content or structure?

      No, prettifying JSON does not change its content or structure. It only changes the formatting and indentation of the JSON data to make it more human-readable. This can be useful for debugging or reading large JSON files.

      Can I prettify JSON that is stored in a database?

      Yes, you can prettify JSON that is stored in a database by first extracting the JSON data from the database, saving it to a file, and then prettifying the file using the jq command or a third-party tool.

      Is JSON prettification the same as minification?

      No, JSON prettification and minification are opposite processes. Prettification involves adding whitespace, indentation, and line breaks to improve the readability of JSON files, while minification involves removing all unnecessary characters to reduce the file size.

      How do I prettify JSON data?

      To prettify JSON data, you can use jq in Linux command prompt. It is a lightweight and flexible command-line JSON processor that can be used to format and transform JSON data. Here’s how to use it:
      cat input.json | jq
      This will read the JSON data from a file called “input.json” and use jq it to format and prettify it, printing the result to the console.

      Total
      0
      Shares