1

I have a json output from an api call, which partially looks like as below. As part of this json, there are many id and name values listed..Now, I want to capture id and name pair together as an array , as part of some steps in the program I get returned with name , I want to compare this name with the name stored in array previously and return the id value corresponding to it. As I have to pass this id value to another rest api call.

Could someone help how can I capture this array through powershell?

$Json = '{
    "value": [
        {
            "id": "1",
            "name": "datafactory.git",
            "size": 0,
            "remoteUrl": "",
            "sshUrl": "",
            "webUrl": "",
            "isDisabled": false
        },
        {
            "id": "2",
            "name": "datafactory",
            "defaultBranch": "refs/heads/main",
            "size": 13569,
            "remoteUrl": "",
            "sshUrl": "",
            "webUrl": "",
            "isDisabled": false
        },
    ]
}'
2
  • 1
    I'd start with ConvertFrom-Json to get your Json into powershell objects and go from there. Commented May 26, 2021 at 6:39
  • Yes, I had done that, but how can I capture both id and name as a pair together, so that I can compare the name with some value obtained from script and output the id value? Commented May 26, 2021 at 6:49

1 Answer 1

1

I would create a hash table for this:

($Json |ConvertFrom-Json).Value |ForEach-Object {
    $HashTable = @{}
} {
    $HashTable[$_.name] = $_.id
}

Usage:

$HashTable.datafactory
2

You might also consider to refer to the complete value property object (instead of just the id):

($Json |ConvertFrom-Json).Value |ForEach-Object {
    $HashTable = @{}
} {
    $HashTable[$_.name] = $_
}

Usage:

$HashTable.datafactory.id
2

$HashTable.datafactory.size
13569
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks iRon, I was trying to do a comparison and printing, but I have an issue there..could u pls suggest.. $reponame = "repo" if($reponame -eq $HashTable.$reponame){ echo $HashTable.$reponame.id } else{ echo "not compared" }
Sorry for the late response, I guess you actually want to see whether the reponame exists: if ($HashTable.Contains($reponame)) { $HashTable[$reponame].id } else { "$reponame doesn't exist" }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.