3 Best Ways to Prettify JSON in Linux

Written by

Reviewed by

Last updated: July 24, 2024

Expert verified

SVG Image

TL;DR

To prettify JSON in the Linux command line, follow these steps:

  1. Install jq: Install jq with sudo apt-get install jq.
  2. Navigate to Directory: Change to your JSON file’s directory using cd /path/to/json/file.
  3. Prettify JSON: Run cat filename.json | jq ‘.’ -C to prettify the JSON.
  4. Save Prettified JSON (optional): Save the output with cat filename.json | jq ‘.’ > outputfilename.json.
  5. Validate JSON Syntax (optional): Validate using sudo apt install python3-demjson and jsonlint outputfilename.json.

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

Struggling with unreadable JSON data? Many developers face this challenge daily, but there’s an easy fix: prettifying JSON. In this guide, I’ll show you how to prettify JSON in Linux, troubleshoot common errors, and use third-party tools for a smoother process. You’ll learn practical steps to turn messy JSON data into a clear, structured format. Whether you’re debugging code or collaborating with your team, these tips will make handling JSON much easier. Let’s get started and simplify your workflow!

What Does “Prettify JSON” Mean?

“Prettify JSON” means making JSON data more readable by humans. JSON (JavaScript Object Notation) is a format used to store and exchange data. It’s common in web development and APIs. However, raw JSON can be hard to read because it often comes in a single long line without any spaces or line breaks.

When you prettify JSON, you add indentation, line breaks, and spaces to the data. This makes it look more organized and easier to understand. Here’s an example:

Minified JSON:

{"name":"John","age":30,"city":"New York"}

Prettified JSON:

{
    "name": "John",
    "age": 30,
    "city": "New York"
}

In the prettified version, each piece of data is on its own line, and the structure is clear.

Benefits of Prettifying JSON

Here are some key benefits of prettifying JSON:

  • Easier to Read and Understand: Prettified JSON is formatted with line breaks and indentation, making it much simpler to read. You can quickly see the structure and contents of the data, which helps when you need to understand or debug it.
  • Simplifies Debugging: When working with JSON data in your code, prettified JSON helps you spot errors more easily. If there’s a mistake in the data, like a missing comma or bracket, it’s much more noticeable in a prettified format
  • Improves Collaboration: If you’re working on a project with others, prettified JSON makes it easier for everyone to read and understand the data. Clear, well-formatted data reduces misunderstandings and mistakes.
  • Better Documentation: Prettified JSON is great for documentation purposes. When you include JSON examples in your project documentation, the clear formatting helps others understand how to use the data correctly.
  • Reduces Errors: Developers are less likely to make mistakes when they can clearly see the structure and contents of the data. According to some studies, well-formatted code and data reduce the number of errors and bugs.

          How to Prettify JSON in Linux

          To prettify JSON in Linux, you can use several methods. First, install jq with sudo apt-get install jq, then run cat filename.json | jq '.' -C to prettify your JSON. Second, use Python by navigating to your file’s directory and running python3 -m json.tool filename.json. Third, install json_xs with sudo apt-get install libjson-xs-perl, then run cat filename.json | json_xs > structured.json. These methods will help you make your JSON data clean and readable.

          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:

                  1. Syntax Errors: JSON data may not prettify correctly due to syntax errors.

                  • Solution: Use a JSON validator tool to check for syntax errors. These tools highlight issues such as missing commas, unmatched braces, or incorrect data types. Websites like jsonlint.com can validate your JSON.

                  2. Large JSON Files: Large JSON files can be slow to prettify and difficult to manage.

                  • Solution: Use command-line tools designed to handle large files, such as jq, which is efficient and can process big datasets. Run cat largefile.json | jq . to prettify a large JSON file using jq.

                  3. Incorrect Encoding: JSON files with incorrect or mixed encoding can cause errors during prettification.

                  • Solution: Ensure your JSON files are in UTF-8 encoding. Convert files to UTF-8 if necessary using the iconv command in Linux: iconv -f original_encoding -t UTF-8 input.json -o output.json.

                  4. Special Characters and Escape Sequences: Special characters and escape sequences can break the JSON structure.

                  • Solution: Ensure all special characters are properly escaped and that your JSON data does not include invalid characters. For example, in JSON, escape double quotes inside strings: {"text": "He said, \"Hello!\""}.

                  5. Choosing the Right Tools: Using a tool that doesn’t suit your specific needs can lead to difficulties in prettifying JSON.

                  • Solution: Choose the right tool based on your requirements. For simple tasks, use jq or Python’s json.tool. For more complex needs, consider using Node.js or text editor plugins. Use jq for command-line operations, python -m json.tool for quick checks, and text editors like VSCode with JSON formatting extensions for development.

                  6. Complex JSON Structures: Complex JSON structures with nested objects and arrays can be hard to prettify and understand.

                  • Solution: Break down complex JSON into smaller, more manageable pieces. Prettify each part separately to ensure clarity. If you have a large JSON object, isolate and prettify individual sections to verify their structure before combining them back.

                  Key Takeaways

                  In this guide, I have covered tools like jq, Python, and json_xs for prettifying JSON in Linux, along with troubleshooting tips for common issues. Third-party tools can also simplify the process, making JSON handling more efficient and effective.

                  If you found this guide helpful, I recommend exploring topics like:

                  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.

                  Ojash

                  Author

                  Ojash is a skilled Linux expert and tech writer with over a decade of experience. He has extensive knowledge of Linux's file system, command-line interface, and software installations. Ojash is also an expert in shell scripting and automation, with experience in Bash, Python, and Perl. He has published numerous articles on Linux in various online publications, making him a valuable resource for both seasoned Linux users and beginners. Ojash is also an active member of the Linux community and participates in Linux forums.

                  Akshat

                  Reviewer

                  Akshat is a software engineer, product designer and the co-founder of Scrutify. He's an experienced Linux professional and the senior editor of this blog. He is also an open-source contributor to many projects on Github and has written several technical guides on Linux. Apart from that, he’s also actively sharing his ideas and tutorials on Medium and Attirer. As the editor of this blog, Akshat brings his wealth of knowledge and experience to provide readers with valuable insights and advice on a wide range of Linux-related topics.

                  Share this article
                  Shareable URL
                  Prev Post

                  How to Change the Time Zone in Ubuntu [5 Best Ways]

                  Next Post

                  6 Effective Ways to Check the Version of a Python Package in Linux?

                  Read next