Heredoc

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the unix category.

Last Updated: 2024-11-21

Certain things, like creating valid JSON, are fiendishly complicated on the command line.

E.g. you might end up with heavy escaping in the likes of

json='{
  "to": '\"$to_party\"',
  "title":"Message Sending",
  "body": '\"$body\"'
}'

or wrapping the bit within the sub-command in both double quotes (normal for JSON entries than then single quotes, as follows):

curl -X POST localhost:8000/api/v1/vehicles -H "Content-Type: application/json"  -d '{
   "csv": "'$(base64 tests/fixtures/data.csv)'",
   "category": "accounts"
}'

This is so complex...and that compexity is due to wrapping in single quot.es

Thee is a better way... The trick is to:

#!/usr/bin/env bash

json() {
 cat <<EOF
 {"to": "$to_party", "title": "Message Sending", "body": "$body"}
EOF
}

curl -X POST "http://api.originstamp.com/v3/timestamp/create"\
 -H "Authorization: 38edeaaa-2a6a-4606-9a3f-3dd9a1411639"\
 -H "Content-Type: application/json"\
 -d "$(json)"

NB Notice how the EOF end needs to be all the way left (i.e. not indented)!