Problem: Sending Multiline JSON via Curl
Sending multiline JSON data through a curl command can be tricky. The issue comes from keeping the JSON structure intact while passing it as a parameter in the command line.
Solutions for Using Multiline JSON in Curl Commands
Using Here Documents for Multiline JSON
Here Documents let you include multiline JSON in curl commands. This method keeps the JSON structure without escaping characters.
To use a Here Document in your curl command:
- Start your curl command as usual.
- Use the
--data-binary @-
option to tell curl to read data from stdin. - Add
<< EOF
after the curl command. - Insert your JSON data on new lines.
- End the JSON data with
EOF
on a new line.
Example:
curl -X POST http://www.example.com/api/users \
-H "Content-Type: application/json" \
--data-binary @- << EOF
{
"field1": "test",
"field2": {
"foo": "bar"
}
}
EOF
Tip: Use Variables in Here Documents
You can use variables within Here Documents to make your JSON payload more dynamic. For example:
NAME="John Doe"
AGE=30
curl -X POST http://www.example.com/api/users \
-H "Content-Type: application/json" \
--data-binary @- << EOF
{
"name": "$NAME",
"age": $AGE,
"active": true
}
EOF
This allows you to easily update the JSON payload with different values without changing the structure.
Escaping Newlines in JSON Payloads
You can also include multiline JSON in curl commands by escaping newlines. This works well for shorter JSON payloads.
To escape newlines:
- Replace each newline with
\n
. - Enclose the JSON payload in single quotes.
Example:
curl -X POST http://www.example.com/api/users \
-H "Content-Type: application/json" \
-d '{"field1": "test",\n"field2": {\n "foo": "bar"\n}}'
Using a Separate JSON File
For larger JSON payloads, you can store the data in a separate file and reference it in the curl command.
To use this method:
- Create a JSON file (e.g.,
payload.json
) with your data. - Use the
@
symbol followed by the filename in your curl command.
Example:
Create a file named payload.json
:
{
"field1": "test",
"field2": {
"foo": "bar"
}
}
Then use this curl command:
curl -X POST http://www.example.com/api/users \
-H "Content-Type: application/json" \
-d @payload.json
This method keeps your JSON data separate from the curl command, making it easier to manage and update.