Rastalamm
Rastalamm

Reputation: 1782

Replace JSON body in Curl request from stdin bash

I am trying to fill one variable in the body of a curl request using input from stdin.

echo 123 | curl -d "{\"query\": {\"match\": {\"number\": @- }}}" -XPOST url.com

Unfortunately, the @- is not being replaced. I would like the body of the request to match the below

{
"query": {
    "match": {
      "number": 123
    }
  }
}

How can I replace the query.match.number value from the stdin?

Upvotes: 2

Views: 1224

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295363

curl doesn't read only a subset of a document from stdin, as you appear to be attempting here -- either it reads the entire thing from stdin, or it doesn't read it from stdin. (If it did what you expect, it would be impossible to put the literal string @- in the text of a documented passed to curl -d without introducing escaping/unescaping behaviors, and thus complicating behavior even further).

To generate a JSON document that uses a value from stdin, use jq:

echo 123 |
  jq -c '{"query": { "match": { "number": . } } }' |
  curl -d @- -XPOST url.com

That said, there's no compelling reason to use stdin here at all. Consider instead:

jq -nc --arg number '123' \
    '{"query": { "match": { "number": ($number | tonumber) } } }' |
  curl -d @- -XPOST url.com

Upvotes: 5

Related Questions