【问题标题】:Powershell curl double quotesPowershell curl 双引号
【发布时间】:2015-11-04 16:18:36
【问题描述】:

我正在尝试在 powershell 中调用 curl 命令并传递一些 JSON 信息。

这是我的命令:

curl -X POST -u username:password -H "Content-Type: application/json" -d "{ "fields": { "project": { "key": "key" }, "summary": "summary", "description": "description - here", "type": { "name": "Task" }}}"

我遇到了 globbing 错误和“不匹配的大括号”以及无法解析主机等问题。

然后我尝试在字符串中的双引号前加上反引号字符,但它无法识别描述json字段中的-字符

谢谢

编辑 1:

当我在常规批处理文件中编写 curl 命令时,我使用了双引号而没有使用单引号。此外,在-d 字符串中,我使用\ 转义了所有双引号,并且该命令有效。

在这种情况下,我的curl 实际上指向 curl.exe。我指定了路径,只是没有在这里列出。我还尝试在-d 周围添加单引号,我得到了:

curl: option -: is unknown curl: try 'curl --help' or 'curl --manual' for more information

似乎无法识别 JSON 中的 - 字符

【问题讨论】:

  • 1) 尝试将 -d 参数用单引号而不是双引号括起来 2) 确保实际上正在调用 curl.exe。如果我没记错的话,powershell 中的curl 可以是Invoke-WebRequest 的别名
  • 你好,请检查上面的编辑
  • 好的,那可能是转义了。在 powershell 中,转义字符是反引号 ` 所以可以尝试在引号 inside json 上使用它
  • @StevenPenny 在我看来,您想清理所有 curl/powershell 线程 ^^。像curl.exe -X POST "https://reqbin.com/echo/post/json" -H "Content-Type: application/json" -d (@{fields=@{project=@{key='key';summary='summary';description='description - here'; type=@{name='Task'}}}} | ConvertTo-Json -Depth 3 -Compress) 这样的东西会适用吗?

标签: json powershell curl character-encoding escaping


【解决方案1】:

将数据导入 curl.exe,而不是试图转义它。

$data = @{
    fields = @{
        project = @{
            key = "key"
        }
        summary = "summary"
        description = "description - here"
        type = @{
            name = "Task"
        }
    }
}

$data | ConvertTo-Json -Compress | curl.exe -X POST -u username:password -H "Content-Type: application/json" -d "@-"

如果您使用@- 作为数据参数,curl.exe 会读取标准输入。

P.S.:我强烈建议您使用正确的数据结构和ConvertTo-Json,如图所示,而不是手动构建 JSON 字符串。

【讨论】:

  • 我可以扩展json结构中的变量吗?就像如果我设置 $var="info",引用 $var 会扩展它?
  • 当然,这是一个常规的 Powershell 对象。您可以在其中使用任何 Powershell 表达式,可以使用循环来构建它,等等。
  • 另外,在$data 变量中,@ 字符是干什么用的?
  • @{} 是用于哈希表的 Powershell 语法(关联数组、键/值存储、字典、对象,无论您如何称呼它)。阅读它,例如这里ss64.com/ps/syntax-hash-tables.html,这里technet.microsoft.com/en-us/library/ee692803.aspx 或官方文档。
  • 好的,谢谢,是什么决定了键和值是否应该声明为字符串(双引号)?就像你有 name = "task",如果它是 "name" = "task" 或 "name" = task?还是转成 JSON 字符串没关系?
【解决方案2】:

简单的方法(用于简单测试):

curl -X POST -H "Content-Type: application/json" -d '{ \"field\": \"value\"}'

【讨论】:

  • 我认为你应该在 PowerShell curl.exe -X POST -H "Content-Type: application/json" -d '{ \"field\": \"value\"}' 中使用 curl.exe,因为 PowersShell 中的 curl 是 Invoke-WebRequest,它与 Linux 中的 cURL 不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-19
  • 2021-07-22
  • 2022-10-17
  • 1970-01-01
  • 2020-12-28
  • 2018-09-02
  • 1970-01-01
相关资源
最近更新 更多