Joost
Joost

Reputation: 1913

Looping through JSON file with PowerShell

How do I loop through all items in a JSON file? The current code just writes all names on one big line:

Get-Content -Raw -Path c:\temp\Environments.Generic.json | ConvertFrom-Json | ForEach-Object {
    Write-Host $_.Name
}

json file:

[
   {
      "Name":"EnableRetry",
      "Description":"Enable retry for Webservice Task",
      "Type":"Boolean",
      "Sensitive":false,
      "Value":true
   },
   {
      "Name":"FolderStageFiles",
      "Description":"Location of stage files",
      "Type":"String",
      "Sensitive":false,
      "Value":"d:\\sources\\"
   },
   {
      "Name":"FtpPassword",
      "Description":"Secret FTP password",
      "Type":"String",
      "Sensitive":true,
      "Value":"Welcome1"
   }
]

Upvotes: 4

Views: 14992

Answers (2)

Joost
Joost

Reputation: 1913

I ended up Select-Object and a ForEach-Object:

$JSON = Get-Content -Raw -Path c:\temp\Environments.Generic.json | ConvertFrom-Json

$JSON | Select-Object -Property Name,Description,Type,Sensitive,Value | ForEach-Object {
    Write-Host $_.Name $_.Value
}

Upvotes: 9

Mark Wragg
Mark Wragg

Reputation: 23355

If you do this:

$JSON = Get-Content -Raw -Path c:\temp\Environments.Generic.json | ConvertFrom-Json

$JSON will be a PowerShell object that contains a collection of objects with all of the properties defined in your JSON file.

Enter $JSON at the console and you'll see the contents of this object.

To access specific properties for specific items in the collection you could do (for example):

$JSON | Where {$_.Name -eq 'FolderStageFiles'} | Select -ExpandProperty Value

Upvotes: 2

Related Questions