Display curl output in readable JSON format in Unix shell script
curl, json, shell
Solution
A few solutions to choose from:
`json` json is a fast CLI tool for working with JSON. It is a single-file node.js script with no external deps (other than `node.js` itself).
$ echo '{"type":"Bar","id":"1","title":"Foo"}' | json
{
"type": "Bar",
"id": "1",
"title": "Foo"
}
Require:
# npm install -g json
json_pp: command utility available in Linux systems for JSON decoding/encoding
echo '{"type":"Bar","id":"1","title":"Foo"}' | json_pp -json_opt pretty,canonical
{
"id" : "1",
"title" : "Foo",
"type" : "Bar"
}
You may want to keep the `-json_opt pretty,canonical` argument for predictable ordering.
jq: lightweight and flexible command-line JSON processor. It is written in portable C, and it has zero runtime dependencies.
echo '{"type":"Bar","id":"1","title":"Foo"}' | jq '.'
{
"type": "Bar",
"id": "1",
"title": "Foo"
}
The simplest `jq` program is the expression `.`, which takes the input and produces it unchanged as output.
For additional `jq` options check the manual
python yq yq: Command-line YAML/XML/TOML processor - jq wrapper for YAML, XML, TOML documents
$ echo '{"type":"Bar","id":"1","title":"Foo"}' | yq
{
"type": "Bar",
"id": "1",
"title": "Foo"
}
The go version go yq doesn't work here
With xidel Command line tool to download and extract data from HTML/XML pages or JSON-APIs, using CSS, XPath 3.0, XQuery 3.0, JSONiq or pattern matching. It can also create new or transformed XML/HTML/JSON documents.
$ echo '{"type":"Bar","id":"1","title":"Foo"}' | xidel -e '$json'
{
"type": "Bar",
"id": "1",
"title": "Foo"
}
with python:
echo '{"type":"Bar","id":"1","title":"Foo"}' | python -m json.tool
{
"id": "1",
"title": "Foo",
"type": "Bar"
}
with nodejs and bash:
echo '{"type":"Bar","id":"1","title":"Foo"}' | node -p "JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 )"
{
"type": "Bar",
"id": "1",
"title": "Foo"
}
Problem
In my Unix shell script, when I execute a curl command, the result will be displayed as below which I am redirecting to file: ``` {"type":"Show","id":"123","title":"name","description":"Funny","channelTitle":"ifood.tv","lastUpdateTimestamp":"2014-04-20T20:34:59","numOfVideos":"15"} ``` But, I want this output to put in the readable JSON format like below in the file: ``` {"type":"Show", "id":"123", "title":"name", "description":"Funny", "channelTitle":"ifood.tv", "lastUpdateTimestamp":"2014-04-20T20:34:59", "numOfVideos":"15"} ``` How do I format the output this way?