乐闻世界logo
搜索文章和话题

How to send and receive JSON data in cURL?

3月6日 23:05

Handling JSON data in cURL is the most common scenario in API testing. Properly sending and receiving JSON data requires setting appropriate headers and using correct parameters.

Sending JSON Data

bash
# Basic JSON POST request curl -X POST https://api.example.com/users \ -H "Content-Type: application/json" \ -d '{"name":"John","email":"john@example.com"}' # Using single quotes to wrap JSON (recommended) curl -X POST https://api.example.com/users \ -H "Content-Type: application/json" \ -d '{"name":"John","age":25}' # Escaping quotes in JSON curl -X POST https://api.example.com/data \ -H "Content-Type: application/json" \ -d "{\"name\":\"John's Data\",\"value\":\"test\"}" # Read JSON data from file curl -X POST https://api.example.com/users \ -H "Content-Type: application/json" \ -d @user.json # Send multi-line JSON using heredoc curl -X POST https://api.example.com/users \ -H "Content-Type: application/json" \ -d @- <<EOF { "name": "John", "email": "john@example.com", "roles": ["admin", "user"], "settings": { "theme": "dark", "language": "en-US" } } EOF

Receiving and Processing JSON Response

bash
# Get JSON response curl https://api.example.com/users # Format JSON output (using jq) curl -s https://api.example.com/users | jq # Extract specific field curl -s https://api.example.com/users | jq '.name' # Show only response body (silent mode) curl -s https://api.example.com/users # Save JSON response to file curl -s https://api.example.com/users -o users.json # Show response headers and formatted JSON curl -i https://api.example.com/users | jq

Common JSON Operation Scenarios

bash
# RESTful API create resource curl -X POST https://api.example.com/products \ -H "Content-Type: application/json" \ -H "Authorization: Bearer token123" \ -d '{ "name": "iPhone 15", "price": 799, "stock": 100 }' # Update resource (PUT) curl -X PUT https://api.example.com/products/123 \ -H "Content-Type: application/json" \ -d '{"price": 699}' # Partial update (PATCH) curl -X PATCH https://api.example.com/products/123 \ -H "Content-Type: application/json" \ -d '{"stock": 50}' # Batch operation curl -X POST https://api.example.com/products/batch \ -H "Content-Type: application/json" \ -d @products.json

Important Parameters

ParameterPurposeExample
-H "Content-Type: application/json"Declare JSON formatMust be set
-d or --dataSend data-d '{"key":"value"}'
-d @filenameRead data from file-d @data.json
-s or --silentSilent modeNo progress info
-oOutput to file-o response.json

Important Notes

  1. Must set Content-Type: Server needs to know the request body is JSON format
  2. Quote handling: Wrap JSON strings with single quotes, use double quotes inside
  3. Special characters: Properly escape special characters in JSON
  4. Encoding: Ensure terminal supports UTF-8 encoding for correct display
标签:cURL