I'm calling Invoke-RestMethod
on a URI which returns JSON like this:
{
"01": {"ID":1, "Name":"Foo"},
"02": {...},
"03": {...}
}
I end up with a PSCustomObject
whose property names are the numbers in the keys, and values are the object graphs, but I want to treat the object as a list of key/value pairs (i.e.: a dictionary). I tried:
(Invoke-RestMethod -Uri $uri) | foreach-object {
$_.ID
$_.Key.ID
}
and so on; but then realized that Foreach-Object
is only iterating once; the return value from Invoke-RestMethod
isn't an IEnumerable
How can I get a collection of the properties and values in the result object?
The [pscustomobject] type accelerator was added in PowerShell 4.0. Prior to adding this type accelerator, creating an object with member properties and values was more complicated. Originally, you had to use New-Object to create the object and Add-Member to add properties. For example: PowerShell Copy.
A key-value pair consists of two related data elements: A key, which is a constant that defines the data set (e.g., gender, color, price), and a value, which is a variable that belongs to the set (e.g., male/female, green, 100). Fully formed, a key-value pair could look like these: gender = male. color = green.
NoteProperties are generic properties that are created by Powershell (as opposed to properties that are inherited from a specific dotnet object type).
Ended up working with this solution:
$js = (Invoke-RestMethod -Uri = $uri)
$hash = @{}
($js | Get-Member -MemberType NoteProperty).Name | Foreach-Object {
$hash[$_] = $js.$_
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With