【问题标题】:Curl and powershell json woesCurl 和 powershell json 问题
【发布时间】:2018-09-27 09:39:27
【问题描述】:

我仍然在让 json 在 powershell 中使用 curl 命令时遇到问题。

即使是一个简单的将某些内容发布到弹性中的请求也会因错误而惨遭失败

意外的字符('D'(代码 68)):期望用双引号来开始字段名称

我已经将脚本简化为基础,只是为了尝试测试 curl 和 json,但仍然会失败

$curlExe = "h:\powershell\esb\elastic\curl\curl.exe"

$elasticdata = @{
        timereceived = "test"
        timesent     = "testing"
        name         = "anon"
        status       = 0
    }

$curldata = $elasticdata | convertto-json -Compress

$elasticoutput = "h:\powershell\esb\elastic\elastic.txt"
$elastichost   = "http://localhost:9200/newtest20/filecopy/?pretty"
$elasticheader = "content-type: application/json"
$elamethod     = "POST"

$curlargs = $elastichost,
            '-X',$elamethod,
            '-d',$curldata,
            '-H',$elasticheader

& $curlexe @curlargs

【问题讨论】:

  • 您的示例数据不包含任何大写字母D,这会导致您的错误消息 - 很难猜出什么不是双引号。我建议您使用 pscx 中的 EchoArgs.exe 之类的工具来查看传递给 cURL 的内容
  • 您是否尝试过在标志上使用双引号?
  • 如果我逐字输入 $curldata 中的内容,然后转义 " 然后它进入命令正常 $curldata = '{\"timereceived\":\"test\",\"timsent\":\"testing\",\"name\":\"anon\",\"status\":0}'
  • @IanRamsden 是的 windows 不喜欢那些单引号:stackoverflow.com/questions/31503754/…

标签: json powershell curl


【解决方案1】:

如果您的服务器正在运行Powershell 2.0,您将没有Invoke-webRequest,但ConvertTo-Json 也会丢失。 我过去也遇到过这个问题,我使用这些函数来解决这个问题

function Invoke-WebRequest([string] $Url, [string] $Method, $BodyObject)
{    
    $request = [System.Net.WebRequest]::Create($Url)
    $request.Method = $Method
    $request.ContentType = "application/json"

    if ($Method -eq "POST")
    {
        try
        {
            $body = ConvertTo-Json20 -InputObject $BodyObject
            $requestStream = $request.GetRequestStream()
            $streamWriter = New-Object System.IO.StreamWriter($requestStream)
            $streamWriter.Write($body)            
        }

        finally
        {
            if ($null -ne $streamWriter) { $streamWriter.Dispose() }
            if ($null -ne $requestStream) { $requestStream.Dispose() }
        }
    }

    $response = $request.GetResponse()    
    if ($response.StatusCode -ne [System.Net.HttpStatusCode]::OK)
    {
        throw "ERROR Could not $Method url [$Url]"
    }

    return $response
}

function ConvertTo-Json20($InputObject){
    Add-Type -Assembly System.Web.Extensions
    $jsonSerializer = New-Object System.Web.Script.Serialization.JavascriptSerializer

    return $jsonSerializer.Serialize($InputObject)
}

【讨论】:

  • 同意Invoke-WebRequest 的提示,但是对于哈希表,我认为原件是正确的。只有在一行上定义多个项目时才需要分号。将它们与在不同行上定义的项目一起添加到此处对输出没有影响。 @Christopher,这真的解决了你的问题吗?
  • 甚至用 ; 改变哈希表没有区别,我查看了输出,它看起来像 json 它只是不喜欢被推送到外部 curl 命令,我使用 curl 因为在服务器上运行的 powershell 版本没有调用 - webrequest 或 invoke-rest
  • 感谢 @rubanov 让我克服了我还没有达到的障碍!
猜你喜欢
  • 2011-09-21
  • 1970-01-01
  • 2020-02-28
  • 2017-03-14
  • 2017-11-03
  • 2021-06-22
  • 1970-01-01
  • 2012-06-01
  • 2022-01-19
相关资源
最近更新 更多