无法获取从ConvertFrom-Json创建的对象的键

时间:2018-03-28 18:31:57

标签: powershell

ConvertFrom-Json创建对象时,它不会创建"正常"对象缺少GetEnumerator()keys

这里有一些演示代码:

$string = '{
  "OBJECT": "SOP10107",
  "OBJECTKEY": "2|OSTD-9999           "
}'

$obj = $string | ConvertFrom-Json

$obj

# no results returned
$obj  | % getEnumerator | % {
  $_.key
  $_.value
}

# no results returned
$obj.keys

$myobj = @{
  "key1" = "val1"
  "key2" = "val2"
}

$myobj

# returns expected result
$myobj | % getEnumerator | % {
  $_.key
  $_.value
}

# returns expected result
$myobj.keys

1 个答案:

答案 0 :(得分:3)

ConvertFrom-JSON创建PSCustomObject类型的普通对象,就像Select-Object ++。

$string = '{
    "OBJECT": "SOP10107",
    "OBJECTKEY": "2|OSTD-9999           "
  }'

$obj = $string | ConvertFrom-Json

#Examine object type and properties
$obj | Get-Member
TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition
----        ----------   ----------
Equals      Method       bool Equals(System.Object obj)
GetHashCode Method       int GetHashCode()
GetType     Method       type GetType()
ToString    Method       string ToString()
OBJECT      NoteProperty string OBJECT=SOP10107
OBJECTKEY   NoteProperty string OBJECTKEY=2|OSTD-9999

#Access known properties directly
$obj.OBJECT
SOP10107

$obj.OBJECTKEY
2|OSTD-9999

如果要循环属性(例如,因为您不知道名称),请使用$obj.psobject.properties返回所有属性的数组。

#List Name and Value for each property. You can replace Select-Object with `Foreach-Object` to loop through them    
$obj.psobject.properties | Select-Object Name, Value

Name      Value
----      -----
OBJECT    SOP10107
OBJECTKEY 2|OSTD-9999