Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display curl output in readable JSON format in Unix shell script

Tags:

json

shell

curl

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?

like image 204
Jams Avatar asked Dec 01 '14 22:12

Jams


People also ask

How do I get Curl response in JSON format?

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.

What is Curl in JSON?

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.

What is JQ in Curl?

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.


1 Answers

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" } 
like image 83
Gilles Quenot Avatar answered Sep 29 '22 14:09

Gilles Quenot