在运行时从JSON对象中提取值。

时间:2022-10-17 16:02:30

I am new to PowerShell am I am trying to figure out how to iterate over JSON objects in PowerShell and extract values.

我是PowerShell的新手,我想知道如何在PowerShell中迭代JSON对象并提取值。

I have a JSON object in a file WIMS.JSON

我在WIMS.JSON文件中有一个JSON对象

{ WIMS:{
    A:{drive:"A"},
    B:{drive:"Z"}
}}

I want to iterate over the objects in WIMS, ie A and B and select the different drive letter in a loop.

我想在WIMS中遍历对象(即A和B),并在循环中选择不同的驱动器号。

I have been able to work out how to get the object names (probably ugly) using

我已经知道如何使用对象名(可能很难看)

$json = (Get-Content "WIMS.json" -Raw) | ConvertFrom-Json
$WIMS = $json.WIMS
$wimNames=$($WIMS| Get-Member -MemberType *Property).Name 
for ($i=0; $i -lt $wimNames.count; $i++) {
    write-host ("Property names are: " + $wimNames[$i])
    $object=$WIMS| select $wimNames[$i]   #does not work
    $object.drive  #does not work
}

But I am unable to figure out how to extract the objects so I can access the fields.

但是我无法弄清楚如何提取这些对象,这样我就可以访问这些字段。

Any pointers would be most appreciated.

如果您有什么建议,我将不胜感激。

2 个解决方案

#1


1  

You are heading on the right track. Using Select-Object with the -Expand argument should get you what you want.

你正朝着正确的方向前进。使用具有-扩展参数的选择对象可以得到您想要的。

$wimNames | ForEach-Object {
    $object = $WIMS | Select-Object -Expand $_
    $object.drive 
}

or

$wimNames | ForEach-Object { $WIMS | Select-Object -Expand $_ | ForEach-Object { $_.drive } }

#2


0  

there is a built-in cmdlet convert-fromjson

有一个内置的cmdlet转换-fromjson

    $js = @"

    { WIMS:{
        A:{drive:"A"},
        B:{drive:"Z"}
    }}


    "@

    $jsobj = $js | ConvertFrom-Json
    $jsobj.WIMS.A

#1


1  

You are heading on the right track. Using Select-Object with the -Expand argument should get you what you want.

你正朝着正确的方向前进。使用具有-扩展参数的选择对象可以得到您想要的。

$wimNames | ForEach-Object {
    $object = $WIMS | Select-Object -Expand $_
    $object.drive 
}

or

$wimNames | ForEach-Object { $WIMS | Select-Object -Expand $_ | ForEach-Object { $_.drive } }

#2


0  

there is a built-in cmdlet convert-fromjson

有一个内置的cmdlet转换-fromjson

    $js = @"

    { WIMS:{
        A:{drive:"A"},
        B:{drive:"Z"}
    }}


    "@

    $jsobj = $js | ConvertFrom-Json
    $jsobj.WIMS.A