I have a simple json that I am trying to get values from in Powershell
$webData = @'
{
"results": [
{
"facet": "266976",
"appid": "266976",
"count": 233206
},
{
"facet": "27096405",
"appid": "27096405",
"count": 85669
}
]
}
'@
$data1 = $webData | ConvertFrom-Json
Write-Output $data1.results.count
When I write output I get values count and not value itself like I do for appid and facet. Desired result: 233206 Current result: 2
I cannot change json. Is there a way for PS not to see it as a count operator? Thank you
CodePudding user response:
As mklement0 notes, in this case the array type's ICollection.Count
property takes precedence over member access enumeration of the array-element property named Count
.
A simple workaround is to use the intrinsic method .ForEach(string PropertyName)
:
$data1.results.ForEach('count')
As Santiago Squarzon notes, the type of ForEach()
output is Collection`1
. If you actually need an array, use the array sub-expression operator @()
or use the workaround suggested by Santiago, using GetEnumerator()
.
$arrayOfCount = @($data1.results.ForEach('count'))
$arrayOfCount = $data1.results.GetEnumerator().Count
Output:
233206
85669
As Santiago Squarzon noted, if you actually want to get the value of count
for the first object only, you can write:
$data1.results[0].Count
Output:
233206
Note that Write-Output
is effectively redundant, because PowerShell implicitly outputs the "result" of any statement. So I've removed it in the samples above.