如何在Powershell中访问嵌套对象的绝对值

时间:2019-06-27 04:46:53

标签: powershell nested-object

嗨,我已经以嵌套对象格式存储了一些数据。类似这样的

$group={
    "share":  {
                  "users":  [
                              {"name" : james
                                "id" :27
                              },
                              {"name" : jeni
                                "id" :18
                              },
                            ]
              }
}

当我尝试检索share或users的值时,它返回null

ping $ group的输出是

{
    "share":  {
                  "users":  [
                                "System.Collections.Hashtable",
                                "System.Collections.Hashtable"
                            ]
              }
}

如何获取用户价值

1 个答案:

答案 0 :(得分:0)

这是你的追求吗?

$group = @'
{
    "share":{
        "users":[
            {
                "name":"james",
                 "id": "27"
            },
            {
                "name":"jeni",
                "id":"18"
            }
        ]
    }
}
'@

$group | 
ConvertFrom-Json

<#
share                   
-----                   
@{users=System.Object[]}
#>


$group | 
ConvertFrom-Json | 
Select -ExpandProperty Share

<#
users                                      
-----                                      
{@{name=james; id=27}, @{name=jeni; id=18}}
#>


$group | 
ConvertFrom-Json | 
Select -ExpandProperty Share | 
Select -ExpandProperty Users

<#
name  id
----  --
james 27
jeni  18
#>


$group | 
ConvertFrom-Json | 
Select -ExpandProperty Share | 
Select -ExpandProperty Users | 
Select Name

<#
name 
---- 
james
jeni
#>


$group | 
ConvertFrom-Json | 
Select -ExpandProperty Share | 
Select -ExpandProperty Users | 
Select id

<#
id
--
27
18
#>


($group | 
ConvertFrom-Json | 
Select -ExpandProperty Share | 
Select -ExpandProperty Users)[0]

<#
name  id
----  --
james 27
#>

*根据我的评论*

# Dot reference the object

$group = @'
{
    "share":{
        "users":[
            {
                "name":"james",
                 "id": "27"
            },
            {
                "name":"jeni",
                "id":"18"
            }
        ]
    }
}
'@


(($group | ConvertFrom-Json)).share

<#
users                                      
-----                                      
{@{name=james; id=27}, @{name=jeni; id=18}}
#>



(($group | ConvertFrom-Json)).share.Users

<#
name  id
----  --
james 27
jeni  18
#>



(($group | ConvertFrom-Json)).share.Users.Name
<#
james
jeni
#>

(($group | ConvertFrom-Json)).share.Users.id
<#
27
18
#>

(($group | ConvertFrom-Json)).share.Users[0]

<#
name  id
----  --
james 27
#>



(($group | ConvertFrom-Json)).share.Users | Select-Object -First 1

<#
name  id
----  --
james 27
#>