我正在尝试将cat输出传递给curl:
$ cat file | curl --data '{"title":"mytitle","input":"-"}' http://api
Run Code Online (Sandbox Code Playgroud)
但input实际上是一个-.
Tom*_*itt 86
我花了一些时间试图解决这个问题并使用以下方法:
cat data.json | curl -H "Content-Type: application/json" -X POST -d @- http://api
Run Code Online (Sandbox Code Playgroud)
小智 12
您可以使用神奇的stdin文件 /dev/stdin
cat data.json | curl -H "Content-Type: application/json" -X POST -d "$(</dev/stdin)" http://api
Run Code Online (Sandbox Code Playgroud)
这也应该有效
curl -H "Content-Type: application/json" -d @data.json http://api
Run Code Online (Sandbox Code Playgroud)
使用-d强制curl为请求隐式使用POST.
尝试
curl --data '{"title":"mytitle","input":"'$(cat file)'-"}' http://api
Run Code Online (Sandbox Code Playgroud)
# 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@-
Run Code Online (Sandbox Code Playgroud)
输出:
...
"json": {
"input": "Try \ud83d\ude01 and \" to verify proper JSON encoding.",
"title": "mytitle"
},
...
Run Code Online (Sandbox Code Playgroud)
请注意,输入文件的内容已正确转义以用作 JSON 值。
jq使用的选项:
--null-input/-n:--rawfile variable-name filename:有关完整详细信息,请参阅jq 手册。
该-d@-选项告诉curl 从STDIN 读取数据。
如果您想在不转义或污染 bash 历史记录的情况下键入/粘贴数据,则可以使用它
cat | curl -H 'Content-Type: application/json' http://api -d @-
Run Code Online (Sandbox Code Playgroud)
这会让您进入cat可以直接输入数据的位置,例如 Shift + Insert 在您的终端中。您以换行符和 Ctrl + D 结束,cat表示您已完成。然后将该数据传递给 curl,您就有了一个可重用的历史记录条目。
| 归档时间: |
|
| 查看次数: |
35464 次 |
| 最近记录: |