📜  linux pretty print json - Shell-Bash (1)

📅  最后修改于: 2023-12-03 14:43:55.461000             🧑  作者: Mango

Linux Pretty Print JSON - Shell/Bash

If you're a Linux user or a programmer who deals with JSON data, you know how important it is to keep JSON well-formatted and easy to read. However, when dealing with large JSON datasets, it can be challenging to parse and maintain. This is where pretty printing JSON comes in.

Pretty printing JSON makes large datasets more readable and easier to understand. In this guide, we will cover how to pretty print JSON in Shell/Bash on Linux.

What is Pretty Printing JSON?

Pretty printing JSON is the process of formatting JSON data to make it more human-readable. When JSON is pretty-printed, it is easier to read and understand data structures, which can help you debug issues in your code.

Consider the following example:

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

Now let's pretty print the JSON:

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

As you can see, pretty printing JSON adds indentation and improves readability.

How to Pretty Print JSON in Shell/Bash

There are many ways to pretty print JSON in Shell/Bash. Some of the most popular tools include jq, python -mjson.tool, and node -e. Let's go through each of these tools in more detail.

Using jq

jq is a popular command-line JSON processor for Linux. It allows you to manipulate and transform JSON data using a simple and expressive syntax.

To pretty print JSON using jq, simply pipe the JSON data to the jq command and use the . operator:

$ echo '{"name":"John","age":30,"city":"New York"}' | jq .
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
Using python -mjson.tool

Python provides a built-in JSON module that includes a command-line tool called json.tool. This tool reads JSON from standard input and pretty prints it to standard output.

To pretty print JSON using python -mjson.tool, simply pipe the JSON data to the json.tool command:

$ echo '{"name":"John","age":30,"city":"New York"}' | python -mjson.tool
{
    "age": 30,
    "city": "New York",
    "name": "John"
}
Using node -e

Node.js is a popular server-side JavaScript framework that includes a command-line tool called node. node can be used to run arbitrary JavaScript code from the command line, including JSON pretty printing.

To pretty print JSON using node -e, simply run the following command:

$ echo '{"name":"John","age":30,"city":"New York"}' | node -e 'console.log(JSON.stringify(JSON.parse(require("fs").readFileSync(0)), null, 2));'
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
Conclusion

In this guide, we have covered how to pretty print JSON in Shell/Bash on Linux. By using tools like jq, python -mjson.tool, and node -e, you can make large JSON datasets more readable and easier to understand.