如何使用curl使用数组输出json对象

Mil*_*bey 87 json curl

我有一系列数据要输入数据库.输入数据的用户界面不适合批量输入,所以我试图制定一个等效的命令行.当我在chrome中检查UI的网络请求时,我看到了一个json对象的PUT请求.当我尝试复制请求时

curl -H 'Accept: application/json' -X PUT '{"tags":["tag1","tag2"],"question":"Which band?","answers":[{"id":"a0","answer":"Answer1"},{"id":"a1","answer":"answer2"}]}' http://example.com/service`
Run Code Online (Sandbox Code Playgroud)

我收到一个错误

curl:(3)[globbing]在pos X不支持嵌套大括号

其中X是第一个"["的字符位置.

我如何PUT包含数组的json对象?

Dan*_*erg 138

您的命令行应该在要在PUT中发送的字符串之前插入-d/ - 数据,并且您要设置Content-Type而不是Accept.

curl -H 'Content-Type: application/json' -X PUT -d '[JSON]' http://example.com/service
Run Code Online (Sandbox Code Playgroud)

使用问题中的确切JSON数据,完整的命令行将变为:

curl -H 'Content-Type: application/json' -X PUT \
-d '{"tags":["tag1","tag2"],"question":"Which band?","answers":[{"id":"a0","answer":"Answer1"},{"id":"a1","answer":"answer2"}]}' \
http://example.com/service
Run Code Online (Sandbox Code Playgroud)

  • -1因为Content-Type(而不是Accept)是在这种情况下应该设置的标头. (4认同)
  • 对于那些想知道的人,[JSON]只是JSON字符串的占位符。不要在JSON字符串周围添加额外的方括号。 (2认同)

Yon*_*nik 78

虽然原始帖子有其他问题(即缺少"-d"),但错误消息更通用.

curl:(3)[globbing]在pos X不支持嵌套大括号

这是因为花括号{}和方括号[]是curl中特殊的通配符.要关闭此通配,请使用" -g "选项.

例如,以下Solr facet查询将失败,而不使用"-g"关闭curl globbing: curl -g 'http://localhost:8983/solr/query?json.facet={x:{terms:"myfield"}}'

  • 这对我来说是正确的解决方案,使用“-g”按预期工作。谢谢@Yonik (6认同)
  • 天哪,我一直在寻找解决我的 GraphQL curl 问题的方法,这对我有帮助。很棒的酱。 (4认同)

mog*_*gul 37

应该提到的是,Accept标题告诉服务器一些我们正在接受的东西,而在这个上下文中的相关标题是Content-Type

我们通常会建议到指定Content-Typeapplication/json发送JSON时.对于curl,语法是:

-H 'Content-Type: application/json'
Run Code Online (Sandbox Code Playgroud)

所以完整的curl命令将是:

curl -H 'Content-Type: application/json' -H 'Accept: application/json' -X PUT -d '{"tags":["tag1","tag2"],"question":"Which band?","answers":[{"id":"a0","answer":"Answer1"},{"id":"a1","answer":"answer2"}]}' http://example.com/service`
Run Code Online (Sandbox Code Playgroud)