我正在尝试将
cat
输出传递给curl:
$ cat file | curl --data '{"title":"mytitle","input":"-"}' http://api
但是
input
实际上是一个-
。
我花了一段时间试图解决这个问题,并让它与以下内容一起工作:
cat data.json | curl -H "Content-Type: application/json" -X POST --data-binary @- http://api
您可以使用神奇的标准输入文件
/dev/stdin
cat data.json | curl -H "Content-Type: application/json" -X POST -d "$(</dev/stdin)" http://api
如果你想输入/粘贴数据而不转义或污染你的 bash 历史记录,你可以使用这个:
cat | curl --json @- https://api.example/
--json
选项是在v7.82.0中添加的,所以如果您的版本较旧,请使用此:
cat | curl --header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--data @- \
https://api.example/
这些会让您进入交互式
cat
,您可以直接输入数据,例如在终端中按 Shift + Insert。
您以换行符和 Ctrl + D(传输结束字符)结束,这向 cat
发出信号表示您已完成。
然后,该数据将传递到 curl
,您就有了一个可重用的历史记录条目。
这也应该有效
curl -H "Content-Type: application/json" -d @data.json http://api
使用 -d 强制curl 隐式使用POST 进行请求。
# Create the input file
echo -n 'Try 😁 and " to verify proper JSON encoding.' > file.txt
# 1. Use jq to read the file into variable named `input`
# 2. create the desired json
# 3. pipe the result into curl
jq -n --rawfile input file.txt '{"title":"mytitle", $input}' \
| curl -v 'https://httpbin.org/post' -H 'Content-Type: application/json' -d@-
输出:
...
"json": {
"input": "Try \ud83d\ude01 and \" to verify proper JSON encoding.",
"title": "mytitle"
},
...
请注意,输入文件的内容已正确转义以用作 JSON 值。
jq
使用的选项:
--null-input/-n:
--rawfile variable-name filename
:请参阅jq 手册了解完整详细信息。
-d@-
选项告诉curl从STDIN读取数据。
尝试
curl --data '{"title":"mytitle","input":"'$(cat file)'-"}' http://api
听起来您想将input
的内容
包装在JSON正文中,然后通过POST请求发送。我认为最简单的方法是首先操作 stdin,然后使用
-d @-
将其推送到curl。一种方法可能如下所示:
cat <(echo '{"title":"mytitle","input":"') file <(echo '"}') \
| curl -d @- http://api
我正在使用
<(echo)
使用 cat
来合并字符串和文件,但几乎肯定有更好的方法。
请记住,这不会逃避
file
的内容,并且您可能会因此遇到问题。