替换来自 stdin bash 的 Curl 请求中的 JSON 正文

Ras*_*amm 2 bash curl

我正在尝试使用来自标准输入的输入填充卷曲请求正文中的一个变量。

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

不幸的是,它@-没有被替换。我希望请求的正文与以下内容相匹配

{
"query": {
    "match": {
      "number": 123
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如何替换query.match.number标准输入中的值?

Cha*_*ffy 5

正如您似乎在此处尝试的那样,curl 不会仅从 stdin 读取文档的子集 - 它要么从 stdin 读取整个文档,要么不stdin 读取文档。(如果它按照您的预期进行,则不可能将文字字符串放入@-传递到的文档的文本中curl -d而不引入转义/取消转义行为,从而使行为进一步复杂化)。

要生成使用 stdin 中的值的 JSON 文档,请使用jq

echo 123 |
  jq -c '{"query": { "match": { "number": . } } }' |
  curl -d @- -XPOST url.com
Run Code Online (Sandbox Code Playgroud)

也就是说,根本没有令人信服的理由在这里使用 stdin。请考虑:

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