Filer json 通过选择特定节点

Filer json by selecting a particular node

我的JSON如下

{
    "Root": [{
        "Child": [{
            "Id": "1"
        }],

        "Child1": [{
            "Id": "2"
        }]
    }]
}

我得到的内容如下

$content = (Get-Content -filepath) -join "`n" | ConvertFrom-Json

我需要的是如果我从脚本作为 Child1 传递,我需要提取以下节点并显示

"Child1": [{
        "Id": "2"
    }]

因为你使用的是 PS3+,而不是连接行(它很慢),通过 -Raw:

将文件作为一个字符串读取
$content = Get-Content $filepath -Raw | ConvertFrom-Json
  • 按名称过滤,显示没有名称的内容:

    $name = 'Child1'
    $content.Root.$name | ConvertTo-Json
    

    在PS2.0:

    $content.Root | Select -expand $name | ConvertTo-Json
    
  • 按名称过滤,显示名称和内容:

    $name = 'Child1'
    ($content.Root | select $name | ConvertTo-Json) -replace '^.|.$',''
    
  • 过滤Id,显示内容:

    $content.Root | ForEach { $_.PSObject.Properties.Value | Where Id -eq 2 } |
        ConvertTo-Json
    
  • 正在按 Id 筛选,显示节点的名称和内容:

    ($content.Root |
         ForEach {
             $_.PSObject.Properties |
                  Where { $_.Value.Id -eq 2 } |
                  ForEach { @{$_.Name = $_.Value} }
         } | ConvertTo-Json
    ) -replace '^.|.$',''