简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM