cURL:将标准输入作为数据发送时,JSON无效 [英] cURL: Invalid JSON when sending stdin as data
问题描述
我可以通过cURL使用以下命令控制Philips Hue灯:
I can control a Philips Hue light with the following command via cURL:
curl -X PUT --data '{"on":true}' "http://<bridgeip>/api/<key>/lights/7/state";
我正在使用函数生成有效负载,因此我想将其通过管道传递给cURL(以从stdin中获取其输入):
I am generating the payload with a function, so I wanted to pipe it to cURL (to take its input from stdin):
onString='{"on":true}';
echo "$onString" | curl -X PUT --data - "http://<bridgeip>/api/<key>/lights/7/state";
但这会引发错误:正文包含无效的json"
but this throws an error: "body contains invalid json"
我不明白这是可行的:
onString='{"on":true}';
curl -X PUT --data "$onString" "http://<bridgeip>/api/<key>/lights/7/state";
有人可以解释吗?
(顺便说一句,当我将函数的输出通过管道传递到 cat
时,结果字符串符合预期,并且在复制并粘贴到jsonlint中后会作为有效JSON输出.)
(Incidentally, when I pipe the output of my function to cat
the resultant string is as expected and when copied and pasted into jsonlint checks out as valid JSON.)
推荐答案
-data-
不会从stdin中获取数据,它只会发送文字-
,
--data -
doesn't fetch data from stdin, it just sends a literal -
,
要从stdin实际获取数据,请使用-data @-
to actually fetch data from stdin, use --data @-
(考虑一下,-data-binary @-
可能是一个更好的主意,我认为在Windows上运行时,它与换行符有所不同,但不是100%肯定)
(come to think of it, --data-binary @-
is probably a better idea, i think it makes a difference with newlines when running on windows, but im not 100% sure)
这篇关于cURL:将标准输入作为数据发送时,JSON无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!