Powershell - How to convert an array to PSCustomObject or json object?

Viewed 33

I have the following json file:

{
    "requestId": "fill-me-in",
    "status": "created",
    "workspace": {
        "id": "123-123-123-123-123-123",
        "isReadOnly": true,
        "isCataloged": false,
        "name": "Widgets",
        "owners":
        [
        ]
    }
}

I need to be able to set values on this object using data from another object. my code looks like this:

 $widgets = (Get-Content './testdata/notification.json')
 Write-Output $widgets.GetType();
 Write-Output $someotherobject.GetType();
 $widgets.workspace.id = $someotherobject.workspace.id

This is what I get back:

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array
True     False    PSCustomObject                           System.Object
 

InvalidOperation: /Users/me/src/functionalTests.ps1:127:1
Line |
 127 |  $widgets.workspace.id = $someotherobject.workspace.id
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | The property 'id' cannot be found on this object. Verify that the property exists and can be set.

Powershell version:

Name                           Value
----                           -----
PSVersion                      7.2.6
PSEdition                      Core
GitCommitId                    7.2.6
OS                             Darwin 21.6.0 Darwin Kernel Version 21.6.0: Sat Jun 18 17:07:22 PDT 2022; root:xnu-8020.140.41~1/RELEASE_ARM64_T6000
Platform                       Unix
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

Edit 1

So I initially tried this to convert from json:

 $widgets = (Get-Content './testdata/notification.json' | ConvertFrom-Json)

But I got the same results.

Fiddled and tried this:

 $widgets = (Get-Content './testdata/notification.json') | ConvertFrom-Json

And it's all good.

0 Answers
Related