Curl is a command-line tool used for transferring data specified with URL syntax. It supports various protocols, including HTTP, HTTPS, FTP, and more. Besides, it is a useful tool for software developers because it can be used to interact with APIs, download files from servers, and much more.
When dealing with JSON data using Curl, we typically do two things: send JSON data and receive JSON data.
Send JSON Data
When interacting with APIs, we often need to send JSON data to the server. Here's how to do it:
curl -X POST -H "Content-Type: application/json" -d '{"key1":"value1", "key2":"value2"}' http://hostname/resource
In the above example, -X POST
instructs Curl to send a POST request. -H "Content-Type: application/json"
sets the content type to JSON, and -d '{"key1":"value1", "key2":"value2"}'
is the data to be sent.
Receive JSON Data
When we want to fetch JSON data from a server, we can simply send a GET request to the server. The server will then respond with the data. Here's an example:
curl -X GET -H "Accept: application/json" http://hostname/resource
In this example, -X GET
instructs Curl to send a GET request, and -H "Accept: application/json"
tells the server that the client expects JSON in return.
Pretty Print JSON
Sometimes, the JSON data we receive can be hard to read because it's all on one line. We can use the jq
command to pretty print the JSON data:
curl -X GET -H "Accept: application/json" http://hostname/resource | jq
In this example, jq
takes the JSON output from the Curl command and pretty prints it.
Note: jq
is a separate tool that you might need to install on your machine. If you are on a Debian-based system, you can install it using sudo apt-get install jq
. For other systems, check the jq homepage.
Remember, replace http://hostname/resource
with the actual URL you want to interact with.