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
| Parameter | Purpose | Example |
|---|---|---|
-H "Content-Type: application/json" | Declare JSON format | Must be set |
-d or --data | Send data | -d '{"key":"value"}' |
-d @filename | Read data from file | -d @data.json |
-s or --silent | Silent mode | No progress info |
-o | Output to file | -o response.json |
Important Notes
- Must set Content-Type: Server needs to know the request body is JSON format
- Quote handling: Wrap JSON strings with single quotes, use double quotes inside
- Special characters: Properly escape special characters in JSON
- Encoding: Ensure terminal supports UTF-8 encoding for correct display