How to Pretty Print JSON output with cURL
This article shows 3 methods or tools to make JSON output easier to read, or "pretty print" the JSON after receiving it with cURL requests.
Table of contents:
- 1. Pretty print JSON with jq
- 2. Pretty print JSON with json_pp
- 3. Pretty print JSON with Python
- 4. References
In the default cURL requests, the JSON output is generally in compact format:
$ curl https://api.cloudflare.com/client/v4/
{"success":false,"errors":[{"code":7000,"message":"No route for that URI"}]}
1. Pretty print JSON with jq
The jq
is a popular JSON tool in the Unix/Linux environment, also described as "sed for JSON data."
$ curl -s https://api.cloudflare.com/client/v4/ | jq .
{
"success": false,
"errors": [
{
"code": 7000,
"message": "No route for that URI"
}
],
"messages": [],
"result": null
}
If we don’t have jq
installed, try installing it using package managers:
- On Ubuntu/Debian –
sudo apt install jq
- On CentOS/RHEL –
sudo yum install jq
- On macOS –
brew install jq
P.S The -s
option in cURL means silent or quiet mode; it makes curl
hide the progress meters and error messages that are normally in output.
2. Pretty print JSON with json_pp
This json_pp
is typically pre-installed on the Unix/Linux environment. It stands for JSON pretty print. It is less powerful than jq
, but it does the job perfectly.
curl -s https://api.cloudflare.com/client/v4/ | json_pp
{
"errors" : [
{
"code" : 7000,
"message" : "No route for that URI"
}
],
"messages" : [],
"result" : null,
"success" : false
}
3. Pretty print JSON with Python
If we have Python installed, we can use the Python’s built-in JSON tool python -m json.tool
or python3 -m json.tool
to format or pretty print JSON output.
curl -s https://api.cloudflare.com/client/v4/ | python3 -m json.tool
{
"success": false,
"errors": [
{
"code": 7000,
"message": "No route for that URI"
}
],
"messages": [],
"result": null
}
json_pp for the win. Thanks mkyong.
Well, you made my day. I have been playing around with Python modules to do this because I did not know about json_pp. Thanks so much sir. Have a great day.
B
Thank you Mkyong!
Good to know it helped.
Thanks mkyong