Powershell 卷曲双引号

问题描述 投票:0回答:3

我正在尝试在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" }}}"

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

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

-
字符

谢谢

编辑1:

当我在常规批处理文件中编写curl命令时,我使用了双引号,没有使用单引号。另外,在

-d
字符串中,我用
\
转义了所有双引号,并且该命令有效。

在这种情况下,我的

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

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

似乎无法识别 JSON 中的

-
字符

json powershell curl character-encoding escaping
3个回答
10
投票

将数据通过管道传输到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 字符串。


5
投票

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

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

0
投票

简单的方法(用于简单测试,带有变量):

curl -X POST -H "Content-Type: application/json" -d "{ \`"field\`": \`"$value\`"}"
© www.soinside.com 2019 - 2024. All rights reserved.