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?
To get JSON with Curl, you need to make an HTTP GET request and provide the Accept: application/json request header. The application/json request header is passed to the server with the curl -H command-line option and tells the server that the client is expecting JSON in response.
The curl “cockpit” is yet again extended with a new command line option: --json . The 245th command line option. curl is a generic transfer tool for sending and receiving data across networks and it is completely agnostic as to what it transfers or even why.
jq is a program described as “ sed for JSON data": You can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.
A few solutions to choose from:
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 additinal jq
options check the manual
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 -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))" { "type": "Bar", "id": "1", "title": "Foo" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With