Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell : retrieve JSON object by field value

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# ).

like image 445
BaltoStar Avatar asked May 15 '13 21:05

BaltoStar


People also ask

Can PowerShell parse JSON?

PowerShell is a great tool to use for manipulating JSON which is used throughout Azure. Have fun scripting! Additional reading: 7.1: ConvertFrom-Json (Microsoft.

What does ConvertFrom-JSON do?

The ConvertFrom-Json cmdlet converts a JavaScript Object Notation (JSON) formatted string to a custom PSCustomObject object that has a property for each field in the JSON string. JSON is commonly used by web sites to provide a textual representation of objects.


1 Answers

$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 
like image 115
David Brabant Avatar answered Sep 28 '22 05:09

David Brabant