PowerShell : retrieve JSON object by field value

BaltoStar picture BaltoStar · May 15, 2013 · Viewed 158.2k times · Source

Consider JSON in this format :

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

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 ) { 

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

Answer

David Brabant picture David Brabant · May 16, 2013
$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