我使用powershell(特别是Azure CLI(从服务中获取数据,向列表中添加值,并向URL发送补丁/帖子。
这是获取数据列表的URL:
$uriList = az rest --method get --uri "https://graph.microsoft.com/beta/applications/$objectId" --header "$header" --query spa.redirectUris | ConvertFrom-Json
这将返回一个字符串数组。
['a', 'b', 'c', 'd', 'e']
if ($uriList -notcontains "f") {
$uriList += "f"
}
$uriListJSON = $uriList | ConvertTo-Json
在上面,我添加了";f";到数组,我想把它发送到如下url:
$body = "{spa:{redirectUris: $uriListJSON}}"
az-rest——方法补丁——uri";https://graph.microsoft.com/beta/applications/$objectId"--标题"$标题"--身体$身体;
我得到一个错误:
Unable to read JSON request payload. Please ensure Content-Type header is set and payload is of valid JSON format."
请就我做错了什么提出建议。我将uriListJSON输出到一个文件中,并在json验证器上运行它,它就通过了。
当我将所有内容硬编码到类似的url时
az rest --method patch --uri "https://graph.microsoft.com/beta/applications/$objectId" --headers $header --body "{spa: {redirectUris: ['a', 'b', 'c', 'd', 'e', 'f']}}"
它就像一个符咒。
从JSON到JSON的转换会产生一个字符串,该字符串符合标准-嵌入双-引用("
(:
PS> ("['a', 'b', 'c', 'd', 'e']" | ConvertFrom-Json) + 'f' | ConvertTo-Json -Compress
["a","b","c","d","e","f"]
由于您将结果字符串传递给外部程序-az
-PowerShell 7.2的可悲现实是,参数中需要额外的手动层-嵌入
"
字符的转义
此可能在未来版本中得到修复,需要选择加入。有关详细信息,请参阅此答案。
因此:
$uriListJSON = ("['a', 'b', 'c', 'd', 'e']" | ConvertFrom-Json) + 'f' | ConvertTo-Json -Compress
$body = "{ `"spa`": { `"redirectUris`": $($uriListJSON -replace '"', '"') } }"
请注意,虽然az
可能没有必要,但上面使用了一个严格符合标准的JSON字符串,其中JSON字符串的逐字部分的属性名也是"..."
-引号,这需要对PowerShell(`"
(进行转义,并对外部程序进行手动-转义;组合:
`"