【问题标题】:PowerShell JSON string escape (backslash)PowerShell JSON 字符串转义(反斜杠)
【发布时间】:2020-05-03 07:29:11
【问题描述】:

我需要使用 PowerShell 脚本将 Json-body HttpPost 到 ASP.NET Core Web Api 端点(控制器)。

$CurrentWindowsIdentity = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$CurrentPrincipalName = $CurrentWindowsIdentity.Identity.Name

# Build JSON payload
$JsonString = @"
{
    "CurrentPrincipalName":"$CurrentPrincipalName"
}
"@

$response = Invoke-RestMethod -Uri "https://webapiendpoint.tld/api/somecontroller" -Method Post -Body $JsonString -ContentType "application/json"

由于变量 $CurrentPrincipalName 的值可以是域\用户名,因此 json 获取无效,因为反斜杠没有正确转义。

web api 的日志出错:

  JSON input formatter threw an exception: 'C' is an invalid escapable character within a JSON string. The string should be correctly escaped. Path: $.CurrentPrincipalName | LineNumber: 15 | BytePositionInLine: 36.
  System.Text.Json.JsonException: 'C' is an invalid escapable character within a JSON string. The string should be correctly escaped. Path: $.CurrentPrincipalName

我如何确保在创建 json 字符串和添加变量时——当然无法控制其值——json 字符串得到正确转义?

我也尝试过 ConvertTo-Json 之类的:

$JsonConverted = $JsonString | ConvertTo-Json

然后 HttpPost 那个对象,但那更糟:

JSON input formatter threw an exception: The JSON value could not be converted to solutionname.model. Path: $ | LineNumber: 0 | BytePositionInLine: 758.

【问题讨论】:

  • 顺便说一句$JsonString | ConvertTo-JsonConvertTo-Json 旨在将哈希表或(自定义)对象转换为 JSON;如果您将已经是 JSON 字符串的内容传递给它,您将得到一个 JSON 字符串值(用文字双引号括起来),并且输入对象结构丢失。试试'{ "foo": 1 }' | ConvertTo-Json

标签: json powershell


【解决方案1】:

创建 JSON 文本的可靠方法是首先将数据构造为哈希表 (@{ ... }) 或自定义对象 ([pscustomobject] @{ ... }),然后通过管道连接到 ConvertTo-Json

$JsonString = @{
  CurrentPrincipalName = $CurrentPrincipalName
} | ConvertTo-Json

这样,PowerShell 会为您执行任何必要的值转义,特别是包括将 $CurrentPrincipalName 值中的文字 \ 字符加倍以确保将其视为 文字。 p>

注意:

  • 根据哈希表的嵌套程度,您可能需要在 ConvertTo-Json 调用中添加 -Depth 参数,以防止更多数据被截断 -请参阅this post 了解更多信息。

  • 如果您有多个属性并希望在 JSON 表示中保留它们的定义顺序,请使用 ordered 哈希表 ([ordered] @{ ... }) 或自定义对象。

【讨论】:

  • 同意。好吧,部分地,只是遇到另一个问题: $CurrentPrincipalIsAdmin = $CurrentWindowsIdentity.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) 需要是 $CurrentPrincipalIsAdmin = $CurrentWindowsIdentity.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) .ToString() 否则:这: $JsonString = @{ CurrentPrincipalIsAdmin = $CurrentPrincipalIsAdmin } | ConvertTo-Json 导致 System.InvalidOperationException:无法将令牌类型“True”的值作为字符串获取。但这超出了这里的范围,我认为必须提出一个新问题
  • @ChristianCasutt 这是一个奇怪的错误,我没想到 - 绝对支持布尔值。如果您有可重现的案例,请发布一个新问题,并提供有关您的特定 PowerShell 版本的详细信息。
  • 尝试:ConvertTo-Json -Depth 1024
猜你喜欢
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多