How To Use Multiline JSON In A Curl Command?

Published September 27, 2024

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:

  1. Start your curl command as usual.
  2. Use the --data-binary @- option to tell curl to read data from stdin.
  3. Add << EOF after the curl command.
  4. Insert your JSON data on new lines.
  5. 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:

  1. Replace each newline with \n.
  2. 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:

  1. Create a JSON file (e.g., payload.json) with your data.
  2. 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.