how to parse json response in powershell

ClaudioM picture ClaudioM · Mar 6, 2018 · Viewed 18.5k times · Source

managed to get the JSON data with

$R= Invoke-WebRequest -Uri $url -Headers $headers -ContentType "application/json"   -Method Get -UseBasicParsing
$x = $R.Content | Out-String | ConvertFrom-Json 

now I've a JSON file like this :

{
  "id": 1000,
  "name_with_namespace": "myProjectName1",

},
{
  "id": 1001,
  "name_with_namespace": "myProjectName2",

},
{
  "id": 1002,
  "name_with_namespace": "myProjectName3",

}

now I need to extract all the occurence of "name_with_namespace" and "id" where "name_with_namespace" = "myProjectName.*"

How can I do it in one shot?

I've tried this:

foreach ($name in $x.name_with_namespace) {
    if ( $name -match ".*myProjectName.*" ) {    
        write-host "$name - $x.id"               
    }   
}

but I got this:

myProjectName1 1000 1001 1002
myProjectName2 1000 1001 1002
myProjectName3 1000 1001 1002

I understand that the issue is on $x.id, how can I get the right value instead of everything ?

my expected output is

myProjectName1 1000
myProjectName2 1001
myProjectName3 1002

Answer

TheMadTechnician picture TheMadTechnician · Mar 6, 2018

You're drilling down a level too far when you define your loop. Just iterate $x and then check against the specific property inside the loop.

foreach ($name in $x) {
    if ( $name.name_with_namespace -match ".*myProjectName.*" ) {    
        write-host "$($name.name_with_namespace) - $($name.id)"               
    }   
}

Edit: On a side note, you can simplify your -match to just "myProjectName" and it will work just as well, and probably faster.