PowerShell:按字段值检索JSON对象 [英] PowerShell : retrieve JSON object by field value

查看:288
本文介绍了PowerShell:按字段值检索JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下格式的JSON:

Consider JSON in this format :

"Stuffs": [
    {
        "Name": "Darts",
        "Type": "Fun Stuff"
    },
    {
        "Name": "Clean Toilet",
        "Type": "Boring Stuff"
    }
]

在PowerShell 3中,我们可以获得一个东西列表:

In PowerShell 3, we can obtain a list of Stuffs :

$JSON = Get-Content $jsonConfigFile | Out-String | ConvertFrom-Json

假设我们不知道列表的确切内容(包括对象的顺序),我们如何检索具有名称"字段特定值的对象?

Assuming we don't know the exact contents of the list, including the ordering of the objects, how can we retrieve the object(s) with a specific value for the Name field ?

蛮力,我们可以遍历列表:

Brute force, we could iterate through the list :

foreach( $Stuff in $JSON.Stuffs ) { 

但是我希望存在一个更直接的机制(类似于C#中的Lync或Lambda表达式).

But I am hopeful there exists a more direct mechanism ( similar to Lync or Lambda expressions in C# ).

推荐答案

$json = @"
{
"Stuffs": 
    [
        {
            "Name": "Darts",
            "Type": "Fun Stuff"
        },

        {
            "Name": "Clean Toilet",
            "Type": "Boring Stuff"
        }
    ]
}
"@

$x = $json | ConvertFrom-Json

$x.Stuffs[0] # access to Darts
$x.Stuffs[1] # access to Clean Toilet
$darts = $x.Stuffs | where { $_.Name -eq "Darts" } #Darts

这篇关于PowerShell:按字段值检索JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆