Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

iteration - how to parse json response in powershell

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...