Powershell中的过滤JSON

Powershell中的过滤JSON,json,powershell,filter,Json,Powershell,Filter,我在Powershell变量中有以下JSON: { "Object1": { "name": "asdf1", "criteria": 2 }, "Object2": { "name": "asdf2", "criteria": 1 } } 我想得到JSON,其中criteria的值是1。

我在Powershell变量中有以下JSON:

{
  "Object1": {
    "name": "asdf1",
    "criteria": 2
  },
  "Object2": {
    "name": "asdf2",
    "criteria": 1
  }
}
我想得到JSON,其中criteria的值是1。因此,结果应如下所示:

{
  "Object2": {
    "name": "asdf2",
    "criteria": 1
  }
}
我尝试使用以下代码:

$json | Get-ObjectMembers | Select-Object | where { $_.value.criteria -eq 1 };
虽然这基本上是正确的方向,但这并不是我想要的,因为结果如下:

{
    "name": "asdf2",
    "criteria": 1
}
查看
Object2
信息是否丢失,一个深度级别是否丢失


如何实现如上所示的预期结果?

本质上,您希望只保留单个输入对象中感兴趣的属性,或者换句话说,删除您不感兴趣的属性

以下是一个PSv4+解决方案:

$json = @'
{
  "Object1": {
    "name": "asdf1",
    "criteria": 2
  },
  "Object2": {
    "name": "asdf2",
    "criteria": 1
  }
}
'@

($json | ConvertFrom-Json).psobject.Properties.
  Where({ $_.Value.criteria -eq 1 }).
    ForEach({ [pscustomobject] @{ $_.Name = $_.Value } }) |
      ConvertTo-Json
上述收益率:

{
  "Object2": {
    "name": "asdf2",
    "criteria": 1
  }
}
解决方案。with_条目临时将属性列表转换为键和值对。(html中的节id很方便)(Json创建者不相信数组?)


什么是GetObjectMembers?
$json = '{
  "Object1": {
    "name": "asdf1",
    "criteria": 2
  },
  "Object2": {
    "name": "asdf2",
    "criteria": 1
  }
}'

$json | jq 'with_entries(select(.value.criteria == 1))'

{
  "Object2": {
    "name": "asdf2",
    "criteria": 1
  }
}