Reputation: 37
I am new to PowerShell am I am trying to figure out how to iterate over JSON objects in PowerShell and extract values.
I have a JSON object in a file WIMS.JSON
{ WIMS:{
A:{drive:"A"},
B:{drive:"Z"}
}}
I want to iterate over the objects in WIMS, ie A and B and select the different drive letter in a loop.
I have been able to work out how to get the object names (probably ugly) using
$json = (Get-Content "WIMS.json" -Raw) | ConvertFrom-Json
$WIMS = $json.WIMS
$wimNames=$($WIMS| Get-Member -MemberType *Property).Name
for ($i=0; $i -lt $wimNames.count; $i++) {
write-host ("Property names are: " + $wimNames[$i])
$object=$WIMS| select $wimNames[$i] #does not work
$object.drive #does not work
}
But I am unable to figure out how to extract the objects so I can access the fields.
Any pointers would be most appreciated.
Upvotes: 2
Views: 2727
Reputation: 2904
there is a built-in cmdlet convert-fromjson
$js = @"
{ WIMS:{
A:{drive:"A"},
B:{drive:"Z"}
}}
"@
$jsobj = $js | ConvertFrom-Json
$jsobj.WIMS.A
Upvotes: 1
Reputation: 1323
You are heading on the right track. Using Select-Object
with the -Expand
argument should get you what you want.
$wimNames | ForEach-Object {
$object = $WIMS | Select-Object -Expand $_
$object.drive
}
or
$wimNames | ForEach-Object { $WIMS | Select-Object -Expand $_ | ForEach-Object { $_.drive } }
Upvotes: 1