如何在PowerShell中遍历JSON数据结构



我是PowerShell的新手,从Python背景中快速学习。

我正在从另一个工具中提取数据,该工具通过REST调用检索数据。

METERS变量以这种格式存储在源中。

{
"500 HR": 500,
"1000 HR": 1000,
"2000 HR": 2000
}

PowerShell代码

#REST call to source
$meter=@{}
Foreach ($item in $origresult.Items)  {
$result = (Invoke-RestMethod -Uri $url  -Headers $headers -Method GET -ContentType application/json -ErrorVariable RespErr)
$meter.Add($item.Name,$result.Value)
}
Write-Host ($meter | Out-String) -ForegroundColor Red

这是输出

Name                           Value
----                           -----
LastUploaded                   2020-12-29T06:38:02
IsEnabled                      1       
METERS                         {...
ORGID                          WHS

如何检索METERS并遍历字典?到目前为止我已经试过了。Python以其简单的数据结构宠坏了我,除非有更简单的方法,否则PowerShell就不那么简单了。

$mymeters = $meter.METERS | ConvertFrom-Json
Write-Host ($mymeters | Out-String) -ForegroundColor Yellow

输出

500 HR   : 500
1000 HR  : 1000
2000 HR  : 2000

以下是我迄今为止尝试过的东西-

$mymeters = [ordered]@{}
" Here is the item $mymeters.Get_Item(500 HR)" #my silly attempt!
# Looping is a no go either - it says specialized ordered dictionary
foreach ($ind in $mymeters) {
" --> $ind"
}

输出

Here is the item System.Collections.Specialized.OrderedDictionary.Get_Item(500 HR)
--> System.Collections.Specialized.OrderedDictionary

我可能错过了一些真正基本的东西,但我无法独自解决!非常感谢您的帮助。我只想遍历METERS哈希表/字典并调用一个函数。

在深入讨论之前,让我们回顾一下PowerShell的一些语法基础,看看我们是否可以重用您的Python直觉:(

成员访问

就像在Python中一样,您可以使用.成员访问运算符通过name引用对象的属性-对于不连续的名称,请使用引号:

$mymeters = $meter.METERS | ConvertFrom-Json
$mymeters.'500 HR'  # evaluates to `500`

字符串表达式

PowerShell中的字符串文字有两种不同的风格:

  • 单引号字符串('Hello World!'(
    • 这些是逐字逐句字符串文字,唯一支持的转义序列是''(文字单引号(
  • 双引号字符串("Hello World!"(
    • 这些是可扩展字符串文字-除非显式转义,否则会自动插入$variable标记和$()子表达式-`是转义符,并且大多数类C语言(`n`t`r等(中的常见序列都是本机识别的

任意表达式(如$dictionary.get_Item('some key')(将不会按原样计算。

为了避免这种情况,我们可以使用-f字符串格式运算符:

$mymeters = [ordered]@{}
"Here is item '500 HR': {0}" -f $mymeters['500 HR']

如果你习惯了Python3的f字符串,-f应该会感觉很熟悉,但需要注意的是-PowerShell的-f运算符是String.Format()的精简包装,并且String.Format()支持基于0的占位符-'{0} {1}' -f 1,2有效,但'{} {}' -f 1,2无效。

另一种选择是将表达式包装在$()子表达式运算符中的双引号字符串文字中:

$mymeters = [ordered]@{}
"Here is item '500 HR': $($mymeters['500 HR'])"

请注意,PowerShell中的字典支持使用[]进行键控索引访问,就像Python一样:(


与Python不同,PowerShell(以及一般的.NET(也具有强大的内省功能。

动态发现和迭代任何对象的属性就像引用一个名为psobject:的特殊成员一样简单

foreach($propertyMetadataEntry in $someObject.psobject.Properties){
"Property: {0,-20} = {1}" -f $propertyMetadataEntry.Name,$propertyMetadataEntry.Value
}

或者在您的情况下:

$mymeters = $meter.METERS | ConvertFrom-Json
foreach($meterReading in $mymeters.psobject.Properties){
"Meter: {0,-20} = {1}" -f $meterReading.Name,$meterReading.Value
# do whatever else you please with $meterReading here :)
}

这将适用于任何标量对象(如ConvertFrom-JsonInvoke-RestMethod返回的对象(。

为了迭代字典中的条目,需要显式调用.GetEnumerator():

$dictionary = [ordered]@{ A = 1; B = 2; C =3 }
foreach($keyValuePair in $dictionary.GetEnumerator()){
"Dictionary Entry: {0} = {1}" -f $keyValuePair.Key,$keyValuePair.Value
}

请检查下面的答案:

1.(我在powershell 5.x上测试了这些东西。powershell的新版本或旧版本(尤其是旧版本(的可能会略有不同

2.(Invoke-Restmethod会自动将json响应转换为powershell对象,因此不需要进一步处理。把所有的赋值都放到一个哈希表中。

$responseJson = '{
"500 HR": 500,
"1000 HR": 1000,
"2000 HR": 2000
}'
$response = $responseJson | ConvertFrom-Json
$nodes = (Get-Member -inputobject $response  -MemberType NoteProperty).Name
$nodes | ForEach-Object {
echo ("Element: $_ Result: " +$response.$_)

}
echo "Another one"
#alternative
foreach ($node in $nodes) {
echo ("Element: $node Result: " +$response.$node)
}

3.(我认为响应格式不正确,所以如果你可以控制restservice,我建议你这样做:

$responseJson = '{
"hr": [
500,
1000,
2000
]
}'
$response = $responseJson | ConvertFrom-Json
$response.hr | ForEach-Object {
echo ("Element: $_ Result: " +$response.$_)

}

最新更新