Using PowerShell to process a JSON string
Custom objects do allow you to add properties, you just have to do it correctly. You need the Add-Member cmdlet.
$o = $s | ConvertFrom-Json # convert the json string to an object
$o.foo = "hello2" # change an existing prop
Add-Member -InputObject $o -MemberType NoteProperty -Name 'bar' -Value "World" # add a new prop
$s2 = $o | ConvertTo-Json # convert back into a json string
It is worth noting that depending on your version of PowerShell that Add-Member line could be simplified to:
$o | Add-Member 'bar' 'World'
I'm not sure what version that syntax became acceptable, but I know it works in v4 and I think it works in v3.
Related videos on Youtube
David Ebbo
Engineering Manager at Google, working in the Kubernetes/Istio org. I previously worked at Microsoft, and was involved in Azure Functions, Azure App Service, ASP.NET, NuGet and various other projects. Twitter: @davidebbo.
Updated on June 04, 2022Comments
-
David Ebbo almost 2 years
Suppose I have a piece of JSON in a PowerShell string, e.g.
$s = '{"foo":"hello"}'
My goal is to turn this into an object that I can manipulate (e.g. changing/adding properties), and then convert back to a json string.
So trying the obvious, I write:
$o = $s | ConvertFrom-Json # convert the json string to an object $o.foo = "hello2" # change an existing prop $o.bar = "World" # add a new prop $s2 = $o | ConvertTo-Json # convert back into a json string
The problem is that the object I get back from
ConvertFrom-Json
is of typePSCustomObject
, which doesn't allow adding properties. So the 3rd line blows up with:Exception setting "bar": "The property 'bar' cannot be found on this object. Verify that the property exists and can be set." At line:1 char:1
Question: what is the best way to approach this without bringing too much complexity?
-
David Ebbo over 9 yearsNice, the simpler
$o | Add-Member 'bar' 'World'
does work. Not as simple as a simple assignment, but good enough. Thanks!