how to parse json response in powershell how to parse json response in powershell powershell powershell

how to parse json response in powershell


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.


So basically you have obtained the json with the parentnode already, so I am not covering that part. Assuming that you already have the parent node, then you can directly do this :

$a=@"{"ParentNode":[    {"id":1000,"name_with_namespace":"myProjectName"},    {"id":1001,"name_with_namespace":"myProjectName2"},    {"id":1002,"name_with_namespace":"myProjectName3"}]}"@ ($a | ConvertFrom-Json).ParentNode

Output:

id name_with_namespace  -- -------------------1000 myProjectName      1001 myProjectName2     1002 myProjectName3

You can parse however you want. No issue on that part. Make sure that your json is structured one that you are receiving from the restAPI. using dot methods, you can go to any level and you can directly select them using select-object as well.

Hope it helps.


ConvertFrom-Json has some odd behavior with pipelines. The issue is that ConvertFrom-Json wraps the JSON array in an array and then passes the whole array down the pipeline as one item. This is fine in most cases, but if the outermost level is a JSON array, then that whole array gets passed as a single object into the pipeline.

Compare:

PS> ConvertFrom-Json '[1, 2, 3]' | ForEach-Object  {": $_"}: 1 2 3PS> (ConvertFrom-Json '[1, 2, 3]') | ForEach-Object  {": $_"}: 1: 2: 3PS> $x = ConvertFrom-Json '[1, 2, 3]'PS> $x | ForEach-Object  {": $_"}: 1: 2: 3PS> ,$x | ForEach-Object  {": $_"}: 1 2 3

Note with that last example we can duplicate the problem with the unary comma operator.

The issue has been reported here for PowerShell Core 6.

Try this code:

$j = @'[    {        "id": 1000,        "name_with_namespace": "myProjectName1"    },    {        "id": 1001,        "name_with_namespace": "myProjectName2"    },    {        "id": 1002,        "name_with_namespace": "myProjectName3"    }]'@($j | Out-String | ConvertFrom-Json) |Where-Object name_with_namespace -match ".*myProjectName.*" |ForEach-Object {    "$($_.name_with_namespace) $($_.id)"}