To prettify JSON in the Linux command line, you try these three methods:
- Use the
jqcommand 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.
- Use the
python3 -m json.tool filename.jsonto display the prettified output of your JSON file in the Terminal.
- You can also pretty print your JSON file with the
json_xscommand 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.
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
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:
jqif 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
- Type y and press Enter to continue with the solution.
- 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.
- Next, open the JSON file in the Linux command line. Navigate to the directory where your JSON file is located using the
- Pipe the JSON data to the
jqcommand, and use the
-Coption to enable color output in the Terminal app with syntax highlighting:
cat filename.json | jq '.' -C
- Once you execute the command, you’ll get the following output:
- If you need this output in a separate JSON file, use the
>operator with the
jqcommand to redirect the output to a new file. Here’s the command to execute in the Terminal window:
cat filename.json | jq '.' > outputfilename.json
- 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.
- Head to the directory path where you have created the file to check the output file.
- Click the file to view the formatted output.
- To validate the newly created JSON file, you may need to install JSON package with the following command:
sudo apt install python3-demjson
- Then, you can use the
jsonlinttool to validate the JSON syntax:
- Here’s an example of JSON files before and after prettification using the jq command:
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:
- In the Terminal app, navigate to the directory containing the JSON file using the
- Run the following command, replacing File.json with the name of your JSON file:
python3 -m json.tool filename.json
- The JSON file will be pretty-printed in the Terminal output.
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:
- Launch the Terminal app and use the
cdcommand to navigate to the directory containing the JSON file.
- Run the following command, replacing
filename.json with the name of your JSON file and
structured.jsonwith 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.
- This command will pretty print the JSON file and save the result to a new file called
- 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:
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:
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.
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.
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.
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.
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
lscommand to list the files in a directory and verify the file’s existence. Alternatively, you can search for that particular file by using the
- 🔒 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 -lcommand 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.jsoncommand 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-prefixcommand. Alternatively, you can prettify JSON data using
--compact-outputoption. 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
--helpoption. If the file format is not supported, you can use certain tools and libraries to convert the file formats, such as
json_normalizein Python. For example, you can use the
csvjsoncommands 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
filecommand to check the file encoding. If it is not supported, use the
iconvcommand 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.jsonto 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
jqto remove unnecessary whitespace:
jq . input.json > output.json
- 🎨 Use Syntax Highlighting: Use a tool that supports syntax highlighting, such as
jqor 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
cpto 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.
To improve JSON readability, make sure to prettify them using Linux command-line tools like
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
What is JSON, and why is it popular?
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.