You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell从JSON数组中提取启用状态的特性名称

PowerShell筛选JSON中enable为true的特性名称

需求

从给定的JSON片段的featureset数组中提取所有enable值为true的特性名称,期望输出:

feature1, feature2, feature4

原代码问题

你之前的代码仅遍历了featureset数组第一个元素的属性(通过featureset[0]指定索引),没有遍历整个数组,也未添加enable为true的筛选逻辑,因此无法得到预期结果。

解决方案

方法1:管道链式处理(简洁高效)

假设你已将JSON内容转为PowerShell对象(若从文件读取,可先用Get-Content+ConvertFrom-Json解析):

# 解析JSON(如果是文件的话)
# $jsn = Get-Content "你的JSON文件路径.json" | ConvertFrom-Json

# 筛选enabled为true的特性,提取名称并拼接成逗号分隔字符串
$enabledFeatureNames = $jsn.abc.comp1.featureset | Where-Object { $_.enable } | Select-Object -ExpandProperty name
$output = $enabledFeatureNames -join ', '
Write-Output $output

方法2:foreach循环(直观易懂)

如果更习惯用循环处理:

$enabledFeatureNames = @()
foreach ($feature in $jsn.abc.comp1.featureset) {
    # 判断enable是否为true,符合条件则收集名称
    if ($feature.enable) {
        $enabledFeatureNames += $feature.name
    }
}
# 拼接成目标格式输出
$output = $enabledFeatureNames -join ', '
Write-Output $output

关键说明

  • 直接遍历$jsn.abc.comp1.featureset即可访问数组中的每一个特性对象,无需指定索引[0]
  • Where-Object { $_.enable }等价于Where-Object { $_.enable -eq $true },PowerShell会自动将布尔值转为判断条件
  • Select-Object -ExpandProperty name会直接提取每个对象的name属性值,而非返回包含该属性的对象

内容的提问来源于stack exchange,提问作者user3462473

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:05:55