1

I looked at similar questions before, but does not exactly answer my issue.

I'm using cURL to send a JSON request, like this:

curl -X POST  -H "Content-Type:application/json" "$HOST" -d '{"uri": "'"$URI"'", "identityKeyValue":"'"`date +%s`"'", "identityKeyType": "bar", "status": "'$STATUS'", "statusDetail": "'"$STATUS_DETAIL"'", "exclusionKeys": [], "monitoredEntity": {"name": "foobar"}, "timestamp":'"`date +%s`"', "metadata": {} }'

It works, but it is very ugly (I'm talking about the part after -d), but I couldn't find something better meeting the following:

  1. Supports variable substitution (like $STATUS)
  2. Support command substitution (like `date +%s`)

Since it's JSON, it obviously needs a lot of doublequotes (")

The command does not have to be one line. I want readability & clarity rather than this messy/hacky look. What do you suggest?

1 Answer 1

1

break it up into multiple steps, and use a printf template:

fmt='{"uri": "%s", "identityKeyValue":"%s", "identityKeyType": "bar", "status": "%s", "statusDetail": "%s", "exclusionKeys": [], "monitoredEntity": {"name": "foobar"}, "timestamp":%d, "metadata": {}}'
time=$(date +%s)
data=$(printf "$fmt" "$URI" $time "$STATUS" "$STATUS_DETAIL" $time)
curl -X POST  -H "Content-Type:application/json" "$HOST" -d "$data"

Also, get out of the habit of using ALL_CAPS_VARNAMES: one day you'll accidentally use PATH and then wonder why your program broke.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .