首页 > 解决方案 > 使用 Powershell 数组中的键创建 JSON

问题描述

我有这个 Powershell Array 对象,其中包含字符串值

[value1,value2,value3,value4,..etc]

我想将它转换为一个 JSON 对象,其中包含一个名为的键,该键value具有数组中的值并使其看起来像这样

[
   { "value" : "value1" },
   { "value" : "value2" },
   { "value" : "value3" },
   { "value" : "value4" },
         ...
]

这在powershell中可能吗?请记住,数组的长度可能为 50,因此它必须遍历数组谢谢

标签: powershellshellpowershell-2.0

解决方案


您可以在 PowerShell v3+ 中执行以下操作:

# Starting Array $arr that you create
$arr = 'value1','value2','value3'

# Create an array of objects with property named value and value of each array value
# Feed created objects into the JSON converter
$arr | Foreach-Object {
    [pscustomobject]@{value = $_}
} | ConvertTo-Json

您可以在 PowerShell v2 中执行以下操作:

$json = New-Object -Type 'System.Text.Stringbuilder'
$null = $json.Append("[")
$arr | foreach-Object {
    $line = "    {{ ""value"" : ""{0}"" }}," -f $_
    $null = $json.Append("`r`n$line")
}
$null = $json.Remove($json.Length-1,1)
$null = $json.Append("`r`n]")
$json.ToString()

推荐阅读