【问题标题】:Filter JSON in Powershell在 Powershell 中过滤 JSON
【发布时间】:2020-07-08 14:19:12
【问题描述】:

我在 Powershell 变量中有以下 JSON:

{
  "Object1": {
    "name": "asdf1",
    "criteria": 2
  },
  "Object2": {
    "name": "asdf2",
    "criteria": 1
  }
}

我想获取 criteria 的值为 1 的 JSON。因此结果应如下所示:

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

我尝试使用以下代码:

$json | Get-ObjectMembers | Select-Object | where { $_.value.criteria -eq 1 };

虽然这基本上是朝着正确的方向发展,但它不是我想要的,因为结果看起来像这样:

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

看到Object2 信息丢失,并且丢失了一个深度级别。

我怎样才能达到如上所示的预期结果?

【问题讨论】:

  • 什么是get-objectmembers?

标签: json powershell filter


【解决方案1】:

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

这是一个 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
  }
}

【讨论】:

    【解决方案2】:

    jq 解决方案。 with_entries 临时将属性列表转换为键值对。 https://stedolan.github.io/jq/manual/#to_entries,from_entries,with_entries(html 中的部分 id 派上用场)(Json 创建者不相信数组?)

    $json = '{
      "Object1": {
        "name": "asdf1",
        "criteria": 2
      },
      "Object2": {
        "name": "asdf2",
        "criteria": 1
      }
    }'
    
    $json | jq 'with_entries(select(.value.criteria == 1))'
    
    {
      "Object2": {
        "name": "asdf2",
        "criteria": 1
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-18
      • 2020-05-15
      • 2022-01-09
      • 1970-01-01
      • 2017-01-30
      • 2021-03-05
      • 1970-01-01
      • 2018-01-21
      • 2021-06-07
      相关资源
      最近更新 更多