JSON uses \
as the 转义字符;例如,\t
是 TAB 字符的转义序列(Unicode 代码点0x9
).
所以,为了使用literal \
- 例如在 Windows 路径中 - 您必须将其转义为\\
.
You could手动转义所有变量值您可以按照以下方式合成 JSON 字符串$caseIterationPath -replace '\\', '\\'
(sic).
However, it is easier to construct regular PowerShell data structures first, and then let ConvertTo-Json do any required escaping on conversion, which would also cover escaping verbatim "
as \"
.[1]
最简单的选择是使用哈希表文字,@{ ... }
;如果您关心在 JSON 转换过程中枚举条目的顺序,请使用ordered哈希表:[ordered] @{ ... }
, 如下所示。
在手头的情况下:
# Sample values.
$caseIterationPath = 'c:\path\to\iteration'
$caseAreaPath = 'c:\path\to\area'
# Construct an array of hashtables to be converted to JSON later.
$Body = @(
[ordered] @{
op = 'test'
path = '/rev'
value = 1
}
[ordered] @{
op = 'add'
path = '/fields/System.IterationPath'
value = $caseIterationPath
}
[ordered] @{
op = 'add'
path = '/fields/System.AreaPath'
value = $caseAreaPath
}
)
# Convert the array to a string containing JSON.
# ConvertTo-Json will perform any required escaping.
$jsonBody = ConvertTo-Json $Body
# Invoke the REST method.
Invoke-RestMethod -Uri "$rootUri/_apis/wit/workitems/$($case.id)?$apiVersion" `
-Method PATCH -ContentType application/json-patch+json `
-Headers @{Authorization= $authorization} `
-Body $jsonBody
在上面的代码中,$jsonBody
最终包含以下内容 - 请注意\
实例被正确转义为\\
:
[
{
"op": "test",
"path": "/rev",
"value": 1
},
{
"op": "add",
"path": "/fields/System.IterationPath",
"value": "c:\\path\\to\\iteration"
},
{
"op": "add",
"path": "/fields/System.AreaPath",
"value": "c:\\path\\to\\area"
}
]
[1] More generally, not constructing the JSON directly as a string also saves you from having to escape syntactic "
chars. inside an overall "..."
string, if string interpolation is needed. E.g., @{ foo = "OS: $env:OS" } | ConvertTo-Json
is simpler than directly constructing "{ `"foo`" = `"OS: $env:OS`" }"