2

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?

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.