Home > Software engineering >  Extract Value from JSON Using PowerShell based on condition
Extract Value from JSON Using PowerShell based on condition

Time:04-27

I have the captured the JSON response in variable $releaseDefinitions. With this i want to extract the "ID" as "4598" when i pass the "name" as "STAGE1-PG-DB" under the "environments" tag using the powershell.

Any help on this is much appreciated.

{
    "id":  516,
    "environments":  [
                        {
                             "id":  4598,
                             "releaseId":  516,
                             "name":  "STAGE1-PG-DB",
                             "status":  "notStarted",
                         },
                        {
                             "id":  4599,
                             "releaseId":  516,
                             "name":  "STAGE2-PG-DB",
                             "status":  "notStarted",
                         },
                        {
                             "id":  4600,
                             "releaseId":  516,
                             "name":  "STAGE3-PG-DB",
                             "status":  "notStarted",
                         } 
                            
                     ]
}

CodePudding user response:

I believe you are asking to get the JSON array object where the name is "STAGE1-PG-DB". Based on the info you've provided, you would do something like this (see my in-line comments)

$releaseDefinitions = Get-Content -Path $inputFileName -Raw | ConvertFrom-Json

# use dot-notation to get the entire Environments array
# pipe the array through using the pipe character
# filter through the array where the key (Name) is equal to your value (STAGE1-PG-DB)
$releaseDefinitions.environments | Where-Object {$_.name -eq "STAGE1-PG-DB"}
  • Related