使用Azure DevOps Pipeline Preview API获取YAML时遇内部错误
解决Azure DevOps Pipeline Preview API的JsonReaderException错误
你的请求触发JsonReaderException是因为PowerShell的Invoke-RestMethod不会自动将哈希表序列化为合法JSON,直接传递哈希表作为-Body会导致请求体格式错误,引发JSON解析失败。
修正后的PowerShell脚本
$method = "Post" $pat = "secret" $token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)")) $headers = @{ Authorization = "Basic $token" } $url = "https://dev.azure.com/organisation/project/_apis/pipelines/193/preview?api-version=7.1-preview.1" # 将哈希表序列化为完整的JSON字符串 $body = @{ previewRun = $true resources = @{ repositories = @{ self = @{ refName = 'refs/heads/main' } } } } | ConvertTo-Json -Depth 10 Invoke-RestMethod -Method $method -Headers $headers -URI $url -Body $body -ContentType "application/json"
关键修正点
- 强制JSON序列化:用
ConvertTo-Json将哈希表转为JSON字符串,Invoke-RestMethod只有在接收字符串类型的-Body时,才会配合-ContentType "application/json"发送符合要求的请求体。 - 设置序列化深度:添加
-Depth 10避免嵌套结构(比如resources下的仓库配置)被默认深度截断,保证JSON结构完整。
额外检查项
- 确认URL中的组织名、项目名、流水线ID(193)拼写准确。
- 如果流水线依赖其他资源(如多个仓库、变量组),需在
resources节点补充对应配置,但当前报错优先解决JSON格式问题。
内容的提问来源于stack exchange,提问作者Scott Richards
相关产品推荐
相关产品推荐

