0

When an object is created from ConvertFrom-Json it doesn't create a "normal" object and is missing GetEnumerator() and keys.

Here's some demonstration code:

$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
Chris76786777
  • 709
  • 1
  • 13
  • 23
  • 2
    `$obj.OBJECT` and `$obj.OBJECTKEY`? [This](https://stackoverflow.com/questions/22002748/hashtables-from-convertfrom-json-have-different-type-from-powershells-built-in-h) is what you are looking for, I guess. – Vivek Kumar Singh Mar 28 '18 at 18:34
  • Whoops. I missed the link on "this". I'll give that a try. – Chris76786777 Mar 28 '18 at 18:39

1 Answers1

5

ConvertFrom-JSON creates a normal object of type PSCustomObject, just like 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

If you want to loop the properties (ex. because you don't known the names), use $obj.psobject.properties which returns an array of all 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
Frode F.
  • 52,376
  • 9
  • 98
  • 114
  • 1
    This works and so did the link Vivek provided. I like your explanation and the solution is a bit easier to understand too. – Chris76786777 Mar 28 '18 at 18:53