powershell - 使用 Powershell 数组中的键创建 JSON
问题描述
我有这个 Powershell Array 对象,其中包含字符串值
[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()
推荐阅读
- node.js - 错误:html-webpack-plugin 无法缩小生成的输出
- scipy - 如何将 pygam 模型转换为 SciPy BSpline
- r - 如何用 gblinear 计算 xgboost 模型的截距
- java - Heroku 没有启动我的 Spring Boot 应用程序(有子模块)
- r - For Loop Auto Arima by 客户
- django - 从 nginx 到 Django 的 REMOTE_USER 的 ProxyPass 出现问题
- c - 如何使用 C 语言将消息从通信器 A 中的一个进程广播到 MPI 中通信器 B 的所有进程?
- microsoft-graph-api - 为 OneDrive 创建订阅时某些租户出现 308
- laravel - Laravel 使用 SurviceProvider 中的 loadViewComponentsAs 方法而不创建包
- python - 使用自举库查找自举置信区间