Using PowerShell to process a JSON string

Using PowerShell to process a JSON string

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 type PSCustomObject, 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?

Solutions/Answers:

Solution 1:

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.

References

Related:  How to unzip a file in Powershell?