乐闻世界logo
搜索文章和话题

How can I pretty-print JSON in a shell script?

1个答案

1

Pretty-printing JSON in shell scripts typically involves using command-line tools like jq. jq is a lightweight and flexible command-line JSON processor. If jq is installed on your system, you can use it to format JSON output.

Here's an example of how to pretty-print JSON in shell scripts using jq:

shell
#!/bin/bash # Assume you have a JSON file named mydata.json json_file="mydata.json" # Use jq to pretty-print JSON content jq '.' "$json_file"

If you obtain JSON output directly from a command, you can do the following:

shell
#!/bin/bash # Assume you have a command that outputs JSON json_output=$(some_command_that_outputs_json) # Use jq to pretty-print echo "$json_output" | jq '.'

If jq is not installed on your system and you cannot install it, you can use Python's json.tool module as an alternative. Most Linux systems include Python, making this a practical solution. Here's how to use Python to format JSON:

shell
#!/bin/bash # Assume you have a JSON file named mydata.json json_file="mydata.json" # Use Python's json.tool module to pretty-print JSON content python -m json.tool "$json_file"

Or, if the JSON data comes from the output of a command:

shell
#!/bin/bash # Assume you have a command that outputs JSON json_output=$(some_command_that_outputs_json) # Use Python to pretty-print echo "$json_output" | python -m json.tool

Using jq is the recommended approach as it not only formats JSON output but also performs complex queries, transformations, and data operations. In contrast, Python's json.tool is primarily intended for formatting.

2024年6月29日 12:07 回复

你的答案