使用JSON多行进行卷曲 [英] Curl with multiline of JSON
问题描述
考虑以下curl命令,是否可以在JSON中使用换行符(不使用minify)并直接在bash中执行(Mac/Ubuntu)
Consider the curl command below, is it possible to allow newline in JSON (without the minify) and execute directly in bash (Mac/Ubuntu)
curl -0 -v -X POST http://www.example.com/api/users \
-H "Expect:" \
-H 'Content-Type: text/json; charset=utf-8' \
-d \
'
{
"field1": "test",
"field2": {
"foo": "bar"
}
}'
当我运行上面的命令时,似乎在second {
处发生了错误
如何修复以上命令?
When I run the command above, seems error occurred at the second {
How to fix the above command?
已更新:实际上,我以前可以无问题地运行命令,不确定为什么最近会发生问题.
Updated: actually I was able to run the command without issue previously, not sure why problem happen recently.
推荐答案
I remembered another way to do this with a "Here Document" as described in the Bash man page and detailed here. The @-
means to read the body from STDIN, while << EOF
means to pipe the script content until "EOF" as STDIN to curl. This layout may be easier to read than using separate files or the "echo a variable" approach.
curl -0 -v -X POST http://www.example.com/api/users \
-H "Expect:" \
-H 'Content-Type: application/json; charset=utf-8' \
--data-binary @- << EOF
{
"field1": "test",
"field2": {
"foo": "bar"
}
}
EOF
注意:使用--trace <outfile>
curl选项可以精确记录 .由于某种原因,此此处文档"方法会删除换行符. (更新:换行符由curl -d选项剥离.已更正!)
NOTE: Use the --trace <outfile>
curl option to record exactly what goes over the wire. For some reason, this Here Document approach strips newlines. (Update: Newlines were stripped by curl -d option. Corrected!)
这篇关于使用JSON多行进行卷曲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!