使用 Powershell 数组中的密钥创建 JSON
Create JSON with Keys from Powershell Array
我有一个包含字符串值的 Powershell 数组对象
[value1,value2,value3,value4,..etc]
我想将其转换为一个 JSON 对象,该对象带有一个名为 value
的键,该键具有数组中的值并使其看起来像这样
[
{ "value" : "value1" },
{ "value" : "value2" },
{ "value" : "value3" },
{ "value" : "value4" },
...
]
在 powershell 中可以吗?请记住,该数组的长度可能为 50,因此它必须遍历该数组
谢谢
您可以在 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()
我有一个包含字符串值的 Powershell 数组对象
[value1,value2,value3,value4,..etc]
我想将其转换为一个 JSON 对象,该对象带有一个名为 value
的键,该键具有数组中的值并使其看起来像这样
[
{ "value" : "value1" },
{ "value" : "value2" },
{ "value" : "value3" },
{ "value" : "value4" },
...
]
在 powershell 中可以吗?请记住,该数组的长度可能为 50,因此它必须遍历该数组 谢谢
您可以在 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()